为什么变量不会改变?

时间:2012-06-10 09:35:49

标签: c++ mingw

我刚学完如何使用随机功能,所以我决定做一个小赌场游戏。但是,我的代码不会更新double Money;变量。也就是说,我无法在此变量中设置,添加或减去值。我无法确定发生这种情况的原因。

这是我的代码:

int main()
{
  double Money;//Variable Money;

  srand ( time(0) );
  int randomNumber;
  randomNumber = (1+(rand() % 10));
  cout << "\nEnter your Starting Money: ";
  int Guess;
  cin >> Money;
  cout << "Your Starting money is: " << Money;
  cout << "\nGuess the number between 1 and 10: ";
  start:
  cin >> Guess;
  if(Guess == randomNumber)
  {
    Money + 10;
    cout << "You were correct! The number was " << randomNumber << "!";
  }
  else
  {
    Money - 10;//Nothing Happens
    cout << "You were wrong! Your money is now: " << Money << "\nRetry Please: ";
    goto start;
  }
  char f;
  cin >> f;
  return 0;
}

4 个答案:

答案 0 :(得分:6)

Money + 10;

是一个没有副作用的声明。你想要

Money += 10;

相当于

Money = Money + 10;

考虑一下,如果你写了

4 + 5; 

您希望4成为9吗? ...

答案 1 :(得分:1)

money - 10;是一个有效的C和C ++表达式,它(概念上)计算该值然后抛弃结果,与42;非常相似。

改为使用money = money - 10;money -= 10;。同样适用于添加。

答案 2 :(得分:1)

您需要将新值分配给Money

Money = Money + 10或者如上所述Money += 10

答案 3 :(得分:0)

如果要更改值,Money + 10不会更改值使用Money = Money + 10 你也可以使用Money + = 10 和btw而不是char f; cin&gt;&gt; F; .. cout&lt;&lt; ENDL;系统( “暂停”);看起来更好