c++ - 尝试使用模数或 fmod,但两者都给我的程序带来问题?

标签 c++ if-statement modulus

我在使用模数除以小数时遇到了问题。我为选项 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/

相关文章:

javascript - 如果源为空,如何将 id 为 false 的 img 标签设置为 false?

ios - 如何使用标签文本 (Int) 值编写 if 条件

batch-file - 为什么 IF 检查在检查表达式之后会忽略 "^<delimter>some_word"?

c++ - operator< 重载错误,操作数无效

c++ - 如何从 pkcs7 文件中获取证书

java - 安卓 OpenCV : Edit ImageView Mat without Reassigning

java - 数组索引的模运算

java - %= 在 Java 中是什么意思?

Java,找到 182.5 % (365/12)

java - 将简单的 java 数组传递给原始 c 数组 swig