C打印问题,小数等于0

时间:2014-09-22 01:46:13

标签: c

我基本上是C的新手,所以请耐心等待。所以基本上我必须创建一个程序来计算每平方英尺面团的数量。重新检查我的数学和调试很长一段时间后;香港专业教育学院发现sradius / INCHES_PER_FEET出现在0。

INCHES_PER_FEET = 12.现在问题是如果我为半径输入等于或大于12的任何值,该功能将正常工作;但如果我输入8,而8/12小于1小数,程序将自动将其等于0,我不知道如何解决这个问题。洞察力将非常感激。

int main(){
//define radius variables
int sradius;
printf("What is the radius of your small pizza, in inches?\n");
scanf("%d", &sradius);
int mradius;
printf("What is the radius of your medium pizza, in inches?\n");
scanf("%d", &mradius);
int lradius;
printf("What is the radius of your large pizza, in inches?\n");
scanf("%d", &lradius);


//define pizzas sold variables
int spizzas;
printf("How many small pizzas do you expect to sell this week?\n");
scanf("%d", &spizzas);
int mpizzas;
printf("How many medium pizzas do you expect to sell this week?\n");
scanf("%d", &mpizzas);
int lpizzas;
printf("How many large pizzas do you expect to sell this week?\n");
scanf("%d", &lpizzas);

//dough calculation per size
double sdough,mdough,ldough;
sdough = (PI*((sradius/INCHES_PER_FEET)*(sradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
mdough = (PI*((mradius/INCHES_PER_FEET)*(mradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
ldough = (PI*((lradius/INCHES_PER_FEET)*(lradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);

//final amount of dough
double fdough;
fdough = ((sdough*spizzas)+(mdough*mpizzas)+(ldough*lpizzas));

//print statement
printf("you need to order %.3f " ,fdough);

return 0;


}

3 个答案:

答案 0 :(得分:2)

在计算之前将所有半径转换为double,结果会得到一个double:

double sdough,mdough,ldough;
sdough = (PI*(((double)sradius/INCHES_PER_FEET)*((double)sradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
mdough = (PI*(((double)mradius/INCHES_PER_FEET)*((double)mradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
ldough = (PI*(((double)lradius/INCHES_PER_FEET)*((double)lradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);

答案 1 :(得分:1)

C通常允许您对单个“数据类型”执行操作。但是,如果您尝试执行此类操作,则C具有一些预设默认值。例如,在下面的代码中,C将a的值赋值为0.0000而不是0.6666,即使您已声明为float:

int main(void)
{
    float a;
    int b=2, c=3;
    a=b/c;
    printf("%f",a);
    return 0;
}

这是因为b和c是声明的整数。在这种情况下使用类型转换,即强制更改声明的数据类型。如果您执行以下操作,上面的代码将为您提供所需的输出:

int main(void)
    {
        float a;
        int b=2, c= 3;
        a=(float)b/(float)c;
        printf("%f",a);
        return 0;
    }

在你的具体情况下,@ cool-guy回答的答案也是如此。

答案 2 :(得分:0)

括号的过度使用(IMNSHO)强制除法为整数。如果你写了

x = PI * sradius / INCHES_PER_FEET * sradius / INCHES_PER_FEET * DOUGH_PER_SQFT;

而不是

x = (PI*((sradius/INCHES_PER_FEET)*(sradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);

这些划分将以浮点形式完成,您将获得更准确的值。将该浮动值分配给int会导致截断而不是舍入,因此可以通过添加一半来提高准确性:

x = PI * sradius / INCHES_PER_FEET * sradius / INCHES_PER_FEET * DOUGH_PER_SQFT + 0.5;

如果充分启用警告诊断,大多数编译器会抱怨隐式转换为int

其他答案是正确的,因为使用类型转换强制类型转换也会得到准确的结果。或者你可以简单地将分母定义为浮点常数:

const float INCHES_PER_FEET = 12.0;

这要求每个除法都以浮点形式完成,即使分子是int