为什么此if语句不输出任何内容? (C ++)

时间:2019-03-20 02:42:04

标签: c++

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

这是我的代码:

#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;
}

1 个答案:

答案 0 :(得分:0)

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

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

模运算符仅适用于整数类型。您正在使用浮点值和产生浮点数的表达式。您需要使用<cmath>标头中的std::fmod()函数来计算浮点数的余数,如下所示:

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