Home > front end >  How to convert floating-point in for-loop to integer in C, for correct calculation
How to convert floating-point in for-loop to integer in C, for correct calculation

Time:05-27

I'm trying to understand C better. In an exercise I had to find out what is wrong about the following code example.

#include <stdio.h>

int main() {
    int count;
    float sum;
    float i;

    sum = 0, count = 0;
    for (i = 1000; i <= 1000.04; i  = .01) {
        sum  = i;
        count  ;
    }
    printf("Sum: %f, Count: %d\n", sum, count);

    return 0;
}

I found out that it's a bad idea to use floating-point in loops because it causes problems bsince it's not accurate. Next step is to rewrite the code, so it does the same thing but without using floating-point in the loop. I'm stuck on this task, I don't know how to replace i <= 1000.04. For i = .01 I guess I could replace it with i and divide it with 100 somewhere else.

Any ideas how to fix it properly?

CodePudding user response:

#include <stdio.h>

int main() {
    int count;
    float sum;
    int i;

    sum = 0, count = 0;
    for (i = 100000; i <= 100004; i  ) {
        sum  = i;
        count  ;
    }
    printf("Sum: %f, Count: %d\n", sum/100, count);

    return 0;
}
  • Related