变量答案是在没有初始化的情况下使用的?

时间:2013-02-10 23:44:04

标签: c++

有任何帮助吗? 当我把这两个数字放入时,它说答案没有被初始化......?

#include <iostream>
using namespace std;
int main()
{
  int num;
  int num2;
  int working;
  int answer;
  int uChoice;
  int work( int one, int two, int todo );
  cout << "Welcome to my Basic Mini-Calculator!" << endl;
  do
    {
      cout << endl << "What do you want to do?" << endl;
      cout << "1) Add" << endl;
      cout << "2) Subtract" << endl;
      cout << "3) Multiply" << endl;
      cout << "4) Divide" << endl;
      cout << endl << "Waiting for input... (enter a number): ";
      cin >> uChoice;
      cout << endl;

    } while( uChoice != 1 && uChoice != 2 && uChoice != 3 && uChoice != 4 );

  switch ( uChoice )
    {
    case 1:
      cout << endl << "You chose addition." << endl;
      cout << "Enter a number: ";
      cin >> num;
      cout << "Enter another number: ";
      cin >> num2;
      working = num + num2;
      cout << "Your answer is: " << answer;
      break;

    case 2:
      cout << endl << "You chose subtraction." << endl;
      cout << "Enter a number: ";
      cin >> num;
      cout << "Enter another number: ";
      cin >> num2;
      working = num - num2;
      cout << "Your answer is: " << answer;
      break;

    case 3:
      cout << endl << "You chose multiplication." << endl;
      cout << "Enter a number: ";
      cin >> num;
      cout << "Enter another number: ";
      cin >> num2;
      working = num * num2;
      cout << "Your answer is: " << answer;
      break;

    case 4:
      cout << endl << "You chose division." << endl;
      cout << "Enter a number: ";
      cin >> num;
      cout << "Enter another number: ";
      cin >> num2;
      working = num / num2;
      cout << "Your answer is: " << answer;
      break;
      return 0;
    }
}

2 个答案:

答案 0 :(得分:3)

正是如此。你宣布回答:

int answer;

然后你多次使用它而不初始化它或为它分配任何值:

cout << "Your answer is: " << answer;

答案 1 :(得分:0)

您使用answer而无需为其分配值,就像警告状态一样: - )

声明部分可能包括:

working = num + num2;
cout << "Your answer is: " << answer;

实际应该有:

answer = num + num2;

代替。

在这种情况下,你可以完全摆脱working