gpt4 book ai didi

c - 使用C显示小数

转载 作者:行者123 更新时间:2023-11-30 21:08:06 24 4
gpt4 key购买 nike

我正在尝试在数字后面显示小数点

#include <stdio.h>

int main() {

int weight;
int miles;
int price;

printf("Enter the packages weight \n");
scanf("%d", &weight);

printf("Enter how many miles to ship the package \n");
scanf("%d", &miles);

if(weight <= 15) {
price = 15;
}
else {
price = (15 + ((weight - 15) * .5 ));
}
if(miles % 500 == 0) {
price += (miles / 500 * 10);
}
else {
price += ((miles / 500 )* 10) + 10;
}


printf("It will cost $%d to ship an item weighing %d pounds %d miles \n", price, weight, miles);
return 0;
}

对于 price = (15+((weight-15)*.5)); 当我在控制台外部插入数字时,它会显示小数位。我可能错过了最简单的事情......

最佳答案

如果您希望在其中存储一些小数部分,您应该将变量 price 的数据类型更改为 float(或 double) .

此外,由于 miles/500 可能会产生一些小数部分(并且 miles 本身可以是 float !),因此也应该将其设为 floatdouble

最后,在 printf 参数中,不要忘记更改格式说明符 %d

对于某些可能产生小数的计算中涉及的所有变量,最好使用 float 据类型,因为这样会更容易理解,如果您希望在输出中看不到小数部分,则将精度设置为0(%.0f)。

关于c - 使用C显示小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com