C编码 - 显示小数点右边的1位数,除非数字是0,否则不显示任何小数位

时间:2015-06-30 00:09:33

标签: decimal precision

我试图只显示小数点右边的一位数,除非该数字为0,否则不会显示小数位。我是初学者,我不能使用任何复杂的编码或条件语句。这是我当前的代码,但在任何情况下都不会显示任何小数位。

#include<stdio.h>
#include<math.h>
#define PI 3.1415927

int main()

{

//Local Declarations
float radius;
float volume;
float SA;
float height;
int dec;
int Dec;
int dec1;
int dec2;
int Dec1;
int Dec2;

//Statements
printf("Enter the radius: ");
scanf("%f", &radius);

height = radius;
volume =  PI * pow( radius, 2.0) * height;
SA = (2.0 * PI * pow( radius, 2.0)) + (2.0 * PI * radius * height);
dec = (volume - (int)volume) * 10.0;
dec1= 0.1 * (int)dec;
dec2 = (dec1 + 2) % (dec1 + 1);
Dec = (SA - (int)SA) * 10.0;
Dec1 = 0.1 * (int)Dec;
Dec2 = (Dec1 + 2) % (Dec1 + 1);

//Output
printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
printf("\nVolume:              %.*f\n",dec2, volume);
printf("Surface Area:         %.*f\n",Dec2, SA);
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

return 0;

} //main

1 个答案:

答案 0 :(得分:0)

您将dec变量声明为整数。你应该使用float。任何强制转换为整数的操作都会导致丢失小数。