我在C ++中制作一个计算器,除非我除以零,否则它可以正常工作。所以我有一个if语句说当一个数字除以零时给出消息“Error Divide buy zero”。然而程序仍然崩溃。
这是我的代码
#include <iostream>
using namespace std;
int main()
{
int a, b, d, s;
d == a/b
cout << "Enter first number\n";
cin >> a;
cout << "Enter second number\n";
cin >> b;
cout << "Select the operation you want\n";
cout << "1.Addition\n";
cout << "2.Subtraction\n";
cout << "3.Multiplication\n";
cout << "4.Division\n";
cin >> s;
switch (s)
{
case 1: cout << "Addition Selected\n"; a+b << endl; break;
case 2: cout << "Subtraction Selected\n"; a-b << endl; break;
case 3: cout << "Addition Selected\n"; a*b << endl; break;
case 4:
if (b==0)
{
cout << "Error Divide by Zero"<< endl;
}
else
{
cout << d << endl;
}
break;
default: cout << "Invalid Selection" << endl;
}
return 0;
}
在我选择操作时的辅助说明中,它并未说明它已被选中。
答案 0 :(得分:1)
您的代码有很多语法错误。
也许这可以帮到你。这巧妙地避免了除零并打印错误信息。
#include <iostream>
using namespace std;
int main() {
int n1, n2, ans;
char op;
cin >> n1 >> op >> n2;
switch (op) {
case '+':
ans = n1 + n2;
break;
case '-':
ans = n1 - n2;
break;
case '*':
ans = n1 * n2;
break;
case '/':
if (n2) {
ans = n1 / n2;
break;
}
default:
cerr << "Invalid Input" << endl;
return 1;
}
cout << ans;
return 0;
}
请参阅http://ideone.com/wa8QJG演示。
答案 1 :(得分:1)
你的行
fs.createWriteSteam > fs.createWriteStream
需要
d == a/b;
它需要在“else”子句中移动。否则,在解释错误的打印之前会发生除0错误。
您也缺少分案的打印件,应该添加。
答案 2 :(得分:0)
您的代码中存在许多拼写错误/语法错误。
这是一个靠近您的代码的工作解决方案:
int main()
{
int a, b, d, s;
cout << "Enter first number\n";
cin >> a;
cout << "Enter second number\n";
cin >> b;
cout << "Select the operation you want\n";
cout << "1.Addition\n";
cout << "2.Subtraction\n";
cout << "3.Multiplication\n";
cout << "4.Division\n";
cin >> s;
switch( s )
{
case 1:
cout << "Addition Selected\n" << a + b << endl;
break;
case 2:
cout << "Subtraction Selected\n" << a - b << endl;
break;
case 3:
cout << "Multiplication Selected\n" << a * b << endl;
break;
case 4:
if( b == 0 )
{
cout << "Error Divide by Zero" << endl;
}
else
{
d = a / b;
cout << d << endl;
}
break;
default:
cout << "Invalid Selection" << endl;
}
return 0;
}