C 乘法和除法
C multiplying and dividing
我是 运行 一个学校程序,运行 是一个 C 计算不正确的简单数学问题。我只是想将我的输出除以一个数字,它返回原始数字。
int main(void)
{
float fcost = 599;
float shipt = (fcost / 120);
shipt = shipt * 120;
printf("%4.0f", shipt);
return 0;
}
如果您只想将数字除以 120,请删除下一行,即删除
发货*=120
因为它使上一行的过程无效。
如果这不是您的意思,请说明。
根据评论中所述,您希望除法结果向下舍入。
为此,您应该使用 int
而不是 float
以便执行整数除法(截断小数部分)而不是浮点除法(保留小数部分) ):
int fcost = 599;
int shipt = (fcost / 120);
shipt *=120;
printf("%d", shipt);
OP 似乎 截断的商数。
如果原始 double
远远超出 int
的范围,则将 FP 数字转换为 int
存在未定义行为 (UB) 的风险。
标准库提供了各种舍入函数来避免上述问题。
#include <math.h>
int main(void) {
float fcost = 599;
// to round to the next lower whole number
float shipt = floorf(fcost / 120);
// to round to the next higher whole number
float shipt = ceilf(fcost / 120);
// to round to the next whole number toward 0
float shipt = truncf(fcost / 120);
shipt *= 120;
printf("%4.0f", shipt);
return 0;
}
我是 运行 一个学校程序,运行 是一个 C 计算不正确的简单数学问题。我只是想将我的输出除以一个数字,它返回原始数字。
int main(void)
{
float fcost = 599;
float shipt = (fcost / 120);
shipt = shipt * 120;
printf("%4.0f", shipt);
return 0;
}
如果您只想将数字除以 120,请删除下一行,即删除
发货*=120
因为它使上一行的过程无效。
如果这不是您的意思,请说明。
根据评论中所述,您希望除法结果向下舍入。
为此,您应该使用 int
而不是 float
以便执行整数除法(截断小数部分)而不是浮点除法(保留小数部分) ):
int fcost = 599;
int shipt = (fcost / 120);
shipt *=120;
printf("%d", shipt);
OP 似乎
如果原始 double
远远超出 int
的范围,则将 FP 数字转换为 int
存在未定义行为 (UB) 的风险。
标准库提供了各种舍入函数来避免上述问题。
#include <math.h>
int main(void) {
float fcost = 599;
// to round to the next lower whole number
float shipt = floorf(fcost / 120);
// to round to the next higher whole number
float shipt = ceilf(fcost / 120);
// to round to the next whole number toward 0
float shipt = truncf(fcost / 120);
shipt *= 120;
printf("%4.0f", shipt);
return 0;
}