gpt4 book ai didi

c - 我如何决定有多少小数,我应该使用 c 中的 float

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:45 25 4
gpt4 key购买 nike

我如何决定我的 float 应使用多少位小数。看我有这个代码`

int main (void)
{
printf("please give me an integer: ");
float num = GetFloat();

float numb;

numb = num;
numb = numb /2;

printf("the half of %f is %f\n", num, numb);
}

但是之后电脑打印出很多零

问:

please give me an integer: 4
the half of 4.000000 is 2.000000

所以 3 位小数而不是 7 位小数可能会更好:

please give me an integer: 10
the half of 10.0 is 5.00

please give me an integer: 3
the half of 3.00 is 1.50

最佳答案

您也可以始终使用 %g 格式说明符。它根据有效位数使用 fe 格式格式化 float 。

int main (void) {
printf("Please give me a floating point number: ");

// Read the value from the user.
float num;
scanf("%f", &num);

// Compute it's half.
float half = num /2;

// Display the result.
printf("The half of %f is %g\n", num, half);
}

关于c - 我如何决定有多少小数,我应该使用 c 中的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628682/

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