gpt4 book ai didi

c - 将我的 float 限制为只有 3 位数字

转载 作者:行者123 更新时间:2023-11-30 16:41:15 25 4
gpt4 key购买 nike

您好,我想检查一下如何将浮点值的位数限制为仅 3 位。基本上以下是我的总和和平均年龄的代码。总和为整数,平均值为 float 。但我想根据我的平均年龄将其限制为仅 3 位数。我尝试使用 %.2f,但如果平均年龄超过 10 岁,那么我的最终答案将包含 4 位数字。请帮帮我。预先非常感谢。

printf("The total age of the 5 individuals are %d\n", sum);
printf("The average age of the 5 individuals are %.2f", average);

最佳答案

%.2f 表示逗号后的 2 位数字。也许有更好的东西,但它有效:

float average = 10,1498; //Example

if (average < 10) {
printf("The average age of the 5 individuals are %.2f", average);
else
printf("The average age of the 5 individuals are %.1f", average);
}

关于c - 将我的 float 限制为只有 3 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334787/

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