gpt4 book ai didi

c++ - 为什么这个 if 语句没有输出任何东西? (C++)

转载 作者:行者123 更新时间:2023-11-28 04:22:02 24 4
gpt4 key购买 nike

以下程序运行并输出 if 语句之前的所有内容。我不知道为什么即使表达式为真,if 语句也没有输出任何内容。

这是我的代码:

#include <iostream>
#include "HeaderCh4-2.h"
#include <iomanip>
using namespace std;

int main()
{
my_info();
int inch1, inch2, totalin, in2ft, remainderin;
float meters, centimeters, miles;
cout << "This program will perform several calculations on two distances, in inches, that you enter.\n\n";
cout << "Please enter the first distance in inches:\t";
cin >> inch1;
cout << endl;
cout << "Please enter the second distance in inches:\t";
cin >> inch2;
cout << endl;
cout << "\n\n";
//output the two distances entered
cout << inch1;
cout << " in" << endl;
cout << inch2;
cout << " in" << endl;
cout << "--------------\n\n";
//calculate total distance in inches and the conversion from iches
to feet
totalin = inch1 + inch2;
in2ft = totalin / 12;
remainderin = totalin % 12;
cout << totalin << " in" << endl;
cout << in2ft << " ft " << remainderin << " in\n\n" << endl;
//conversion to metric
meters = totalin * 0.0254;
centimeters = totalin % (254 / 10000);
cout << centimeters;
if (totalin > 36)
{
float meters, centimeters;
meters = totalin * 0.0254;
centimeters = totalin % (254 / 10000);
cout << "Metric conversion of " << totalin << " inches";
cout << setw(10) << setprecision(1) << fixed << meters;
cout <<
setw(5) << left << " m";
cout << setw(10) << setprecision(1) << fixed << centimeters;
cout << setw(5) << left << " m";
}
else
{
cout << "Metric conversion of ??? is ???";
}
return 0;
}

最佳答案

您代码中的以下行未按预期进行评估(也在 comment 中指出),因为它会导致被零除导致未定义的行为:

centimeters = totalin % (254 / 10000); // (254 / 10000) = 0.0254 -> 0 (integer)

模数运算符仅适用于整数类型。您正在使用产生 float 的浮点值和表达式。您需要使用 std::fmod()来自 <cmath> 的函数像这样计算 float 余数的标题:

centimeters = std::fmod( totalin, (254.0f / 10000.0f) );

关于c++ - 为什么这个 if 语句没有输出任何东西? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252791/

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