c++ - 将浮点数乘以 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;
}
解决方案
除以零检查应在除法输入块内。
else if (input == '/') {
if (num1 == 0 || num2 === 0) {
cout << "error" << endl;
}
}
在您的代码中,由于输入是“/”,因此不会执行任何其他 else 块。
推荐阅读
- xcode - 如何使用 azure dev Ops 并行运行 xcuitests?
- javascript - Why my moving button in the div can't react?
- node.js - How to convert a react app to an npm module?
- plot - Sympy Binomial plotting
- java - error when trying to discard dependency and build a project with maven
- c# - Ambiguity between field in an Interface
- php - Bootstrap HTML - 选项卡作为单选按钮表单
- angular - How can I make mat-tree from REST API (MongoDB and express) using Angular 8?
- testcontainers - Testcontainers ; Running @Testcontainers Tests inside docker [Running Docker inside Docker]
- user-interface - 如何在颤动中剪辑标签栏容器的边缘?