【问题标题】:Can somebody please check where I went wrong? [closed]有人可以检查我哪里出错了吗? [关闭]
【发布时间】:2020-03-14 16:54:41
【问题描述】:

我是 C++ 新手,我遇到了这个问题,其中乘法和减法无法正常工作。我已经尝试过运行/编译它们,除法和加法都是唯一可以正常工作的。

对于我来说,会发生什么情况是 减法 会相加并在每个答案之前留下一个 (-),以及与乘法类似的情况。

#include<iostream>
using namespace std;

int main(){

char a,b,c,d;
char operation;
int x,y,z, op = 0;
int num[2];

cout<<"\n\n\n\t\t\tCALCULATOR "; 
cout<<"\n\t\t\t a - ADDITION";
cout<<"\n\t\t\t b - SUBTRACTION";
cout<<"\n\t\t\t c - MULTIPLICATION";
cout<<"\n\t\t\t d - DIVISION";
cout<<"\n\n\n ";
cout <<"\n\t\t\tChoose your operator: "; cin >> operation;

switch(operation){
    case 'a':
    case 'A':

        cout<< "\n\t\t\tyou chose ADDIION";
        cout<< "\n\t\t\tinput numbers: ";
        for (x = 0; x < 2; x++)
        {
            cin >> num[x];
            op += num[x];
        }

        cout << "\n\t\t\tSum = " << op << endl;

    break;

    case 'b':
    case 'B':

        cout<< "\n\t\t\tYou chose Subtraction";

        cout<< "\n\t\t\tinput numbers: ";
        for (x = 0; x < 2; x++)
        {
            cin >> num[x];
            op *= num[x];
        }

        cout << "\n\t\t\tDifference = " << x << endl;
    break;

    case 'c':
    case 'C':

        cout<< "\n\t\t\tYou chose Multiplication";

        cout<< "\n\t\t\tinput numbers: ";
        for (x = 0; x < 2; x++)
        {
            cin >> num[x];
            op *= num[x];
        }

        cout << "\n\t\t\tProduct = " << x << endl;
    break;

    case 'd':
    case 'D':

        cout<<"\n\t\t\tYou chose Division";

        cout<<"\n\t\t\tinput numbers: ";
        for (x=0; x < 2; x++)
        {
            cin >> num[x];
            op /= num[x];
        }
        cout << "\n\t\t\tQuotient"<< x << endl;
    break;  
}
return 0;
}

【问题讨论】:

  • 再看看你的减法代码。你到底在做什么?
  • 等问题中,运算结果是op,而不是索引x

标签: c++ arrays switch-statement


【解决方案1】:

请注意,您正在使用减法

op *= num[x];

相当于

op = op * num[x];

这是两个数字相乘而不是相减。

还要注意,对于这些操作,op 的初始值为 0,仅适用于加法。对于减法,您将拥有

op = 0 - num[x]

对于乘法,您将拥有

op = 0 * num[x]

对于Division,您将拥有

op = 0 / num[x]

确保您正在对预期值(即 x[0] 和 x[1])进行操作,并且您正在打印 op。看起来您正在为减法、乘法和除法打印 x。

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2022-06-10
    • 2022-06-14
    • 2011-08-13
    相关资源
    最近更新 更多