首页 > 解决方案 > 将浮点数乘以 0 时,我得到了 inf,而我想说“错误”

问题描述

我是一名初学者 c++ 程序员,这是我的家庭作业之一,除了最后一个问题,当用户输入一个数字除以零时,它应该说“错误”,但我得到了 inf 作为我的输出. 我做了一个 if 语句,说 if (num1 == 0 || num2 == 0) 它会说错误,但事实并非如此!

#include <iostream>
#include <iomanip> 
using namespace std;



int main() {

    double num1 {};
    double num2 {};
    char input {};
    double result {};

    cout << "Enter your calculations: ";
    cin >> num1 >> input >> num2;

    cout << fixed << setprecision(2);

    if (input == '+') {
        result = num1 + num2;
    } else if (input == '-') {
        result = num1 - num2;
    } else if (input == '/') {
        result = num1 / num2;
    } else if (input == '*') {
        result = num1 * num2;
    } else if ( num1 == 0 || num2 == 0 ) 
        cout << "error";

     cout << "Answer: "<< result << endl;

    }

标签: c++if-statementzero

解决方案


除以零检查应在除法输入块内。

else if (input == '/') {
    if (num1 == 0 || num2 === 0) {
        cout << "error" << endl;
    }
}

在您的代码中,由于输入是“/”,因此不会执行任何其他 else 块。


推荐阅读