我在使用模数除以小数时遇到了问题。我为选项 3 和 4 切换到 fmod,但是当您选择选项 3 和 4 时,程序会在选择英寸后停止工作。我想继续使用模数,因为我们在类里面已经做到了,但是我我也对其他方式持开放态度。
int inches, choice, feet, yards;
float centimeters, meters;
float locentimeters, lometers;
int meternum, centnum;
meternum = 39.370;
centnum = .39370;
cout << "Display the entered length in:\n"
<< "1.\tfeet\n"
<< "2.\tyards\n"
<< "3.\tcentimeters\n"
<< "4.\tmeters\n\n"
<< "Enter your choice:\n";
cin >> choice;
cout << "Please enter the length in inches:\n";
cin >> inches;
if (choice == 1)
{
feet = (inches / 12);
cout << fixed << showpoint << setprecision(1);
cout << feet << " feet" << inches % 12 << " inches\n";
}
else if (choice == 2)
{
yards = (inches / 36);
cout << fixed << showpoint << setprecision(1);
cout << yards << " yards" << inches % 36 << " inches\n";
}
else if (choice == 3)
{
centimeters = (inches / .39370);
cout << fixed << showpoint << setprecision(1);
locentimeters = (inches % centnum);
cout << centimeters << locentimeters << " centimeters\n";
}
else if (choice == 4)
{
meters = (inches / 39.370);
cout << fixed << showpoint << setprecision(1);
lometers = (inches % meternum);
cout << meters << lometers << " meters\n";
}
else
cout << "That is an invalid entry.\n";
最佳答案
问题:
运营商%
应具有积分型。和 centnum
本身就是一个 int
.你用 .39370
初始化它转换为 int
是 0。这就是为什么在菜单 3 中你得到除以零的原因:
locentimeters = (inches % centnum); // diveide by 0
和meternum
也是一个 int
.您将其初始化为 39.370
, 转换为 int 将是 39
.这就是为什么在菜单 4 中你会得到不准确的结果:
lometers = (inches % meternum); // meternum is 39 and not 39.370
如果将常量定义为 double 而不是 int 是不够的:
-
%
需要和整型除法器。所以用double
你将无法编译。 -
fmod
被定义为整数商的余数。
解决方案:
第一步是用正确的类型定义常量:
const double meternum = 39.370;
const double centnum = .39370;
然后你替换%
通过 fmod()
.同时结果fmod
仅当您使用 floor()
取除法的组成部分时才有意义.像这样:
...
else if (choice == 3)
{
centimeters = floor(inches / centnum);
cout << fixed << showpoint << setprecision(1);
locentimeters = fmod(inches,centnum);
cout << centimeters << locentimeters << " centimeters\n";
}
else if (choice == 4)
{
meters = floor(inches/ meternum);
cout << fixed << showpoint << setprecision(1);
lometers = fmod(inches,meternum);
cout << meters << lometers << " meters\n";
}
...
小提示:一个好习惯是要么使用带有双字面量的 double ,例如 3.370,要么使用带有 float 字面量的 float ,例如 3.370f强>。如果您将 float 与双文字混合使用,您可能会遇到微妙的舍入问题。
关于c++ - 尝试使用模数或 fmod,但两者都给我的程序带来问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28571768/