Why won't my program work? It is supposed to add numbers from a formula 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
. This will always returns 0, except when i
is 1
. This happens because 1 / i
is evaluated as an Euclidean division with the remainder being discarded.
The reason this is evaluated like this is because 1
and i
are both integer. 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
. The other way is to make 1
be of floating point type: suma = suma - 1.0 / i
or suma = suma - (float)1 / i
.
The for loop started from 0. so the first iteration returns divide by zero error. second iteration will return 1/1=1 and will work good, but from third iteration it will return 0, because you are using int. Try starting the for loop from 1 and typecast i to float.
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:
#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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.