我一直试图在乘法运算中将小数点显示为2位小数:
if (operation == multiplication)
{
printf("\n\n You have chosen to perform a multiplication operation\n\n");
printf("Please enter two numbers seperated by a space (num1 * num2): ");
scanf("%f %f", &number1, &number2);
total = number1 * number2;
printf("\n%f times %f is equal to: %f", number1, number2, total);
}
所以如果我输入 0.5 & 30 我会 15 而不是15.000000,如果我输入 0.5 & 15 我会得到7.50而不是7.5000000。
我仍然很擅长使用C编程,一般情况下,所以详细解释真的很棒。 感谢。
答案 0 :(得分:3)
将printf
与精确说明符一起使用:
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 10.0, y = 10.5, dummy;
printf("%.*f\n", (modf(x, &dummy) == 0) ? 0 : 2, x);
printf("%.*f\n", (modf(y, &dummy) == 0) ? 0 : 2, y);
return 0;
}
输出:
10
10.50
答案 1 :(得分:1)
只需指定小数位,如下所示:
printf("\n%.2f times %.2f is equal to: %.2f", number1, number2, total);
//^^See here ^^ ^^
有关printf()
的详情,请参阅此处:http://www.cplusplus.com/reference/cstdio/printf/