开关状态和操作;我哪里出问题了? [关闭]

问题描述 投票:0回答:1

我删除了有关开关语句代码的旧帖子/问题,因为我有一些明显的错别字,并创建了一个新文件。我的问题是,我仍然对该操作仍如何使用加法或等于声明的0感到困惑。我确实尝试使用(x = 0; x <2; x--)运行它,但最终结果为0。

这里是代码:

#include<iostream>
using namespace std;

int main(){

    int x, num[2], ans = 0;
    char operation;
    int y,z;

    cout<<"\n===== Operation =====";
    cout<<"\n A - Addition";
    cout<<"\n B - Subtraction";
    cout<<"\n C - Multiplication";
    cout<<"\n D - Division";
    cout<<"\n E - Exit";
    cout<<"\n\n Select operation (A,B,C,D or E to Exit): "; cin >> operation;

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

            cout << "\n You selected ADDITION";
            cout << "\n Input 2 numbers: ";
            for ( x = 0 ; x < 2 ; x++ )
            {
                cin >> num[2];
                ans += num[2];
            }

            cout << "\n The answer is: " << ans << endl;
        break;

        case 'b':
        case 'B':

            cout << "\n You selected SUBTRACTION";
            cout << "\n Input 2 numbers: ";
            for ( x = 0 ; x < 2 ; x++ )
            {
                cin >> num[2];
                ans -= num[2];
            }

            cout << "\n The answer is: " << ans << endl;

        break;

        default:

            cout << "were you trying something else??? \n unless you are looking for this error. Congratulations!"; 
    }
    return 0;
}
c++ switch-statement
1个回答
-1
投票

您想做什么

for ( x = 0 ; x < 2 ; x++ ) {
  cin >> num[x];
}
ans = num[0] + num[1];

代替

for ( x = 0 ; x < 2 ; x++ ) {
  cin >> num[2];
  ans += num[2];
}

以及类似的减法方法。

还请注意数组索引num[2],第三个数组元素不适合两个元素int num[2];的数组。

© www.soinside.com 2019 - 2024. All rights reserved.