编写C程序以查找系列的总和 [英] Write a C program to find the sum of the series

查看:87
本文介绍了编写C程序以查找系列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

系列如图所示

1+(1/2)^ 2 +(1/3)^ 3 + ...



我创建了一个代码,不幸的是,它一直显示1.000000或2.000000作为答案。任何人都可以帮我吗?



什么我试过了:



The series is as shown
1+ (1/2)^2 + (1/3)^3 +...

I've created a code,but unfortunately,it keeps showing 1.000000 or 2.000000 as the answer.Can anyone help me please??

What I have tried:

#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
    int i,n;
    float sum=1.0,x;
    printf("Enter limit");
    scanf("%d",&n);
    for(i=2;i<=n;i++)
    {
        x=1/i;
        sum=sum+pow(x,i);
    }
    printf("The sum is %f",sum);
    getch();
}

推荐答案

简单: i 是一个整数。因此,对于任何大于1的值, 1 / i 为零,因为整数根本没有派系部分,因此所有小数值都被丢弃,所有结果都为零超过1和1为 1/1



将i的声明更改为float,或者将其转换为:

Simple: i is an integer. So for any value greater than one, 1/i is zero, because integers do not have a factional part at all, so all fractional values are discarded, leaving zero for all results over 1, and 1 for 1/1

Change the declaration of i to float, or cast it:
x = 1.0 / (float)i;


您的输出格式为float。



阅读并学习 printf 语法。



更改代码以解决问题:

Your output is formatted as float.

Read and learn the printf syntax.

Changing your code to should solve the problem:
printf("The sum is %d",(int) sum);





你最好使用更大的数据类型double



You better use the greater data type double

double sum = 0;


有一个工具可以让你看到你的代码正在做什么,它的name是调试器。它也是一个很好的学习工具,因为它向你展示了现实,你可以看到哪种期望与现实相符。

当你不明白你的代码在做什么或为什么它做它做的时候,答案就是答案是调试器

使用调试器查看代码正在执行的操作。只需设置断点并查看代码执行情况,调试器允许您逐行执行第1行并在执行时检查变量。



调试器 - 维基百科,免费的百科全书 [ ^ ]



掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]

调试器在这里向您展示您的代码正在做什么,您的任务是与什么进行比较应该这样做。

调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。
There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于编写C程序以查找系列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆