显然,这只是代码的一小部分。
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%5.2d", &x);
printf("The number you have entered is %5.2d\n" ,x);
Run Code Online (Sandbox Code Playgroud)
这会自动四舍五入我输入的数字吗?还是有其他方法可以做到这一点?
编辑:
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%lf", &x);
x = x + 0.05;
printf( "The number you have entered is %5.2lf\n", x);
Run Code Online (Sandbox Code Playgroud)
我这样做了,但是我考虑到有人对printf所说的话,只是“改变”了它的读出方式。因此,这显然不是正确的方法。我应该实现pow()函数吗?这可以以某种方式工作吗?
编辑2:
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%lf", &x);
x = x + 0.05;
printf( "The number you have entered is %5.2lf\n", x);
Run Code Online (Sandbox Code Playgroud)
好吧,iv到了要点,如果我输入一个数字,它将四舍五入为整数。35.21将舍入到35,而35.51将舍入到36等。等等
我如何将35.2178舍入为35.22和35.2135舍入为35.21。如何获得小数的某些幂而不是整数?
您确实不应将“舍入”值存储在浮点变量中。浮点数的不准确性将破坏这一点-您的5.10可能会变成5.099999999941892,这仅仅是因为实现可能无法完全存储5.10。
或者,读取整数,将其乘以100,然后将其转换为int(将其舍入为零)。这样可以使您的计算准确无误。