使用printf()输出正确数量的十进制位置?
当我输入2
时,我希望获得此输出:
value: 2.4
但是当我进行乘法时,我会得到这个:
value: 2.400000
这是我的代码:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
我该怎么办?
When I enter 2
, I wish to get this output:
value: 2.4
But when I do the multiplication, I am getting this:
value: 2.400000
This is my code:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
%。nf
其中n
是小数点之后的数字数。在您的用例中,%。1F
:printf(“结果:%.1f”,结果)
。您的代码中还有其他一些问题。您正在使用
scanf()
,但是您没有检查其返回值。这可能会导致您的代码断开。scanf()
返回其成功解析的参数。如果出于任何原因失败,它不会改变您给出的参数,并且它使输入缓冲区完整。这意味着,每当您再次尝试并从输入缓冲区读取时,它将自动失败,因为这将导致无限循环。
为了解决问题,您需要清除输入缓冲区,如果
scanf()
失败。通过清除缓冲区,我的意思是阅读并丢弃所有内容,直到遇到newline(当您以前按下 Enter 时)。您可以在主机中使用它:
样本输出:
You can specify how many digits you want to print after the decimal point by using
%.Nf
whereN
is the number of digits after the decimal point. In your use case,%.1f
:printf("Result: %.1f", result)
.There are some other issues in your code. You are making use of
scanf()
, but you are not checking its return value. This may cause your code to break.scanf()
returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail sinceThis will result in an infinite loop.
To solve the issue, you need to clear the input buffer in case
scanf()
fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.You can use it in your main like that:
Sample output: