我想在C程序中避免“浮点错误”(I want to avoid 'floating point error' in C program)
我想避免在此代码中出现“浮点错误”。
此代码的目的是获得“整数的平均值”,但“整数”的数量受用户输入的限制。 请帮帮我。
#include <stdio.h> int main(void) { int num=0; int limit; int result=0; printf("number of integer: "); scanf("&d", &limit); while(num<limit) { int output; printf("Input integer : "); scanf("%d", &output); result += output; num++; } printf("average of total integer: %d \n", result/limit); return 0; }谢谢你的阅读。
I would like to avoid 'floating point error in this code.
A purpose of this code is to gain 'The average of whole numbers' but the number of 'whole numbers' is limited by the input of users. Please help me.
#include <stdio.h> int main(void) { int num=0; int limit; int result=0; printf("number of integer: "); scanf("&d", &limit); while(num<limit) { int output; printf("Input integer : "); scanf("%d", &output); result += output; num++; } printf("average of total integer: %d \n", result/limit); return 0; }Thank you for reading.
最满意答案
除2个整数后,结果也是整数。
要返回一个浮点数,您需要将其中一个参数转换为浮点数。
所以你的最后一行变成了
printf("average of total integer: %f \n", result/(float)limit);When you divide 2 integers, the result is also an integer.
To return a float, you need to cast one of the arguments as a float.
So your last line becomes
printf("average of total integer: %f \n", result/(float)limit);更多推荐
发布评论