简体   繁体   中英

C++ Calculator Exits

I have a problem with my first program in C++.I wrote this calculator but for some reason when I type the operation character it quits.It doesn't show any error or something,it just exits. This is the code from Visual C++

#include <iostream>

using namespace std;

int  main()
{
    float n1;
    float n2;
    float n3;
    int op;
    cout << "Welcome to my calculator" << endl;
    cout << "Type the first number: ";
    cin >> n1;
    cout << "Type the second number: ";
    cin >> n2;
    cout << "Type the number for the operation" << endl;
    cout << "1 = addition" << endl;
    cout << "2 = subvision" << endl;
    cout << "3 = multiply" << endl;
    cout << "4 = division" << endl;
    cin >> op;
    if(op == 1)
    {
        n3 = n1 + n2;
        cout << "The result is " << n3 << endl;
    }
    if(op == 2)
    {
        n3 = n1 - n2;
        cout << "The result is " << n3 << endl;
    }
    if(op == 3)
    {
        n3 = n1 * n2;
        cout << "The result is " << n3 << endl;
    }
    if(op == 4)
    {
        n3 = n1 / n2;
        cout << "The result is " << n3 << endl;
    }
    return 0;
}

You might want to look at the switch statement instead of your multiple if s. Then your default statement can catch what is happening when none of your expected cases match.

switch (op)
{
case 1:
{
   // add
   break;
}
// other cases
default
{
   // something unexpected, print an error
}
}

You could fix that whit inserting

system("pause");

at the end just before the return (if you're coding under windows)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM