我想在C程序中避免“浮点错误”(I want to avoid 'floating point error' in C program)

编程入门 行业动态 更新时间:2024-10-25 13:17:34
我想在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);

更多推荐

本文发布于:2023-07-30 01:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我想   浮点   错误   程序   avoid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!