What's wrong with cin >> num1, num2?

后端 未结 3 1977
予麋鹿
予麋鹿 2021-01-26 05:42
#include 
using namespace std;

int main() {
  char choice;
  int solution, num1, num2;

  cout << \"Menu\";
  cout << \"\\n========\";
  cou         


        
3条回答
  •  春和景丽
    2021-01-26 06:32

    You are using cin wrong. Do this instead :

    cin >> num1 >> num2;
    

    (And it is always nice to let the user know what to type with one cout or two :)).

    You could do cin only once just after cin >> choice, and before the switch. It will save you some lines and will respect the credo :

    Do not repeat yourself.

    You don't check for divide by zero. If the user try to do num1 / 0, your program will crash.

    The return 0 in case 'X' is not necessary and your break won't be reached, so you could remove the return and you will meet the main's return 0 instead, keeping the switch nice and clean.

    In case '/' you cast num2 to double. I don't see why you print the result of a int casted to a double. My guess is you wanted the result to be a double. In that case, you would do :

    solution = num1 / (double)num2; 
    

    and change solution to be a double.

    Lastly, I advise you always initialize your variables since you could face the case where you use unitialized variables and get undefined behavior.

提交回复
热议问题