【问题标题】:C coding- Display 1 digit to the right of the decimal, unless the digit is a 0, then don't display any decimal placesC 编码- 显示小数点右侧 1 位,除非该位为 0,否则不显示任何小数位
【发布时间】:2015-06-30 00:09:33
【问题描述】:

我试图只显示小数点右侧的一位数字,除非该数字为 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

【问题讨论】:

    标签: decimal precision


    【解决方案1】:

    您将 dec 变量声明为整数。您应该改用浮点数。任何转换为​​整数的操作都会导致小数点丢失。

    【讨论】:

    • 如果将它们更改为浮点数,我认为打印语句和 % 模数会出现其他错误。我还需要改变什么?
    • 这个网站link 谈论使用 printf 方法格式化字符串。根据该网站,您的字符串格式应为 %.1f
    猜你喜欢
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2017-09-14
    • 2010-11-10
    • 2014-11-22
    • 1970-01-01
    相关资源
    最近更新 更多