简体   繁体   English

C-数字总和

[英]C - Sum of numbers

Why won't my program work? 为什么我的程序不起作用? It is supposed to add numbers from a formula 1-(1/2)+(1/3)...+(1/999)-(1/1000)= 应该从公式1-(1/2)+(1/3)... +(1/999)-(1/1000)=加上数字

#include <stdio.h>
#include <math.h>
int main () {
 int i, j;
 float  suma;
 suma = 0.f;
 for (i=0; i<1000; i++) {
    if (i%2==0) {
        suma=suma - 1/i;
    } else {
        suma=suma + 1/i;
    }
 }
 printf("%f", suma);

}

Divide by zero !! 除以零!

int main () {
 int i;
 float  suma;
 suma = 0.0f; 
 for (i=1; i<1000; i++) {  //fix loop, start from 1
    if (i%2==0) {
        suma=suma - 1.0f/i; // Use 1.0, (1/i will be evaluated as int)
    } else {
        suma=suma + 1.0f/i;
    }
 }
 printf("%f", suma);

}

Try printing 1 / i with i being an int . iint尝试打印1 / i This will always returns 0, except when i is 1 . 除非i1 ,否则它将始终返回0。 This happens because 1 / i is evaluated as an Euclidean division with the remainder being discarded. 发生这种情况是因为1 / i被评估为欧几里得除法 ,其余部分被舍弃了。

The reason this is evaluated like this is because 1 and i are both integer. 之所以这样评估,是因为1i都是整数。 You need to either the numerator or the denominator to be of floating point type. 您需要分子或分母为浮点类型。

One way is to cast i to a float, so your code would look like this: suma = suma - 1 / (float)i . 一种方法是将i suma = suma - 1 / (float)i转换为浮点数,因此您的代码应如下所示: suma = suma - 1 / (float)i The other way is to make 1 be of floating point type: suma = suma - 1.0 / i or suma = suma - (float)1 / i . 另一种方法是使1为浮点类型: suma = suma - 1.0 / isuma = suma - (float)1 / i

The for loop started from 0. so the first iteration returns divide by zero error. for循环从0开始。因此第一次迭代返回除以零的错误。 second iteration will return 1/1=1 and will work good, but from third iteration it will return 0, because you are using int. 第二次迭代将返回1/1 = 1并可以正常工作,但是从第三次迭代将返回0,因为您使用的是int。 Try starting the for loop from 1 and typecast i to float. 尝试从1开始for循环,然后键入i浮动。

You will get much higher accuracy if you apply some math first. 如果首先应用一些数学运算,则将获得更高的准确性。 Your series: 您的系列:

1 - 1/2 + 1/3 - 1/4 + ... + 1/999 - 1/1000

can be rewritten as: 可以重写为:

(1 - 1/2) + (1/3 - 1/4) + ... + (1/999 - 1/1000)

or as: 或为:

1/(1*2) + 1/(3*4) + ... + 1/(999*1000) 

Now, you can write a program to perform calculation. 现在,您可以编写一个程序来执行计算。 However, you should use double type to improve accuracy and cast integer to double to make sure that your series are added as double numbers: 但是,您应该使用double类型来提高准确性,并使用整数将double转换为double来确保将序列添加为double数:

#include <stdio.h>
#include <math.h>
int main() {
    int i;
    double sum = 0;
    for (i=1; i<1000; i+=2) {
        sum += 1/(i*(i+1.)); // 1. to force cast to double
    }
    printf("%g", sum);
}

herein a simple program 这里是一个简单的程序

float j = 1.0f;
float suma = 0.0f;
int i = 1;

for (i=1; i <= 1000; i++) {
   suma += j/i;
   j = j * (-1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM