gpt4 book ai didi

C++计算器,不能被0除

转载 作者:行者123 更新时间:2023-12-03 03:07:02 32 4
gpt4 key购买 nike

我有这个问题,我想显示如果0/0,输出是:“不能将0除以自身”。如何调整我的代码以便可以显示该输出?如果是这样,我应该使用什么代码才能实现我的目标?
下面是我的代码:

#include <iostream>
using namespace std;
double isAdd(double x, double y);
double isSub(double x, double y);
double isMult(double x, double y);
double isDiv(double x, double y);
int main() {
cout << "Calculator\n";
double oneV, twoV;
char choice = 'a';
cout << "Enter 2 Values : \n";
cin >> oneV;
cin >> twoV;
cout << "Enter Operation to Use: ( a / s / m / d) \n";
cout << "a = addition, s = subtraction, m = multiply, d = divide\n";
cin >> choice;
if (choice == 'a') {
cout << "The Sum is : " << isAdd(oneV, twoV);
}
if (choice == 's') {
cout << "The Difference is : " << isSub(oneV, twoV);
}
if (choice == 'm') {
cout << "The Product is " << isMult(oneV, twoV);
}
if (choice == 'd') {
cout << "The Quotient is " << isDiv(oneV, twoV);
}
}

double isAdd(double x, double y) {
double answer = x + y;
return answer;
}
double isSub(double x, double y) {
double answer = x - y;
return answer;
}
double isMult(double x, double y) {
double answer = x * y;
return answer;
}
double isDiv(double x, double y) {
double answer = x / y;
return answer;
}

最佳答案

if ('d' == choice) {
if (0 == twoV)
//cout << "Cannot divide 0 by itself\n";
cout << "Division by zero.\n";
else
cout << "The Quotient is " << isDiv(oneV, twoV);
}

提示:

  • 摆脱所有这些if并使用switch
  • 在这种情况下可以与 0 进行比较,但如果您使用的是计算值,则需要检查是否“接近零”。请参阅https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon 。这是由于浮点精度限制。
  • 如果用户输入 asmd 以外的内容,您的代码将自动退出。您应该显示类似“无效输入”的内容。
  • 您也没有考虑输入大小写:即 Aa

关于C++计算器,不能被0除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60067158/

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