gpt4 book ai didi

c - 我想在 C 程序中避免 'floating point error'

转载 作者:行者123 更新时间:2023-12-05 01:36:18 25 4
gpt4 key购买 nike

我想避免“此代码中的浮点错误”。

此代码的目的是获得“整数的平均值”,但“整数”的数量受用户输入的限制。请帮助我。

#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;
}

感谢阅读。

最佳答案

当您将 2 个整数相除时,结果也是一个整数。

要返回 float ,您需要将其中一个参数转换为 float 。

所以你的最后一行变成了

printf("average of total integer: %f \n", result/(float)limit);

关于c - 我想在 C 程序中避免 'floating point error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22783177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com