[英]How to convert floating-point in for-loop to integer in C, for correct calculation
I'm trying to understand C better.我试图更好地理解 C。 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
.我被困在这个任务上,我不知道如何替换
i <= 1000.04
。 For i += .01
I guess I could replace it with i++
and divide it with 100 somewhere else.对于
i += .01
我想我可以用i++
替换它,然后在其他地方除以 100。
Any ideas how to fix it properly?任何想法如何正确修复它?
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.