我可以在“if 语句”中声明一个变量吗?

yel*_*iah 0 c++ variables if-statement declaration

我正在编写一个“自动售货机”程序,我需要有 5 个项目,其中 3 个项目的成本是整数,另外 2 个项目的成本是小数。

我只if在此代码中使用语句,但我的cost变量有错误。

我做错了什么?

代码如下:

#include <iostream>
using namespace std;

int main() {

  cout << "Vending Machine" << endl;
  cout << "----Items------" << endl;
  cout << "1. Popcorn: $2" << endl;
  cout << "2. Coconut Clusters: $3" << endl;
  cout << "3. Granola Bar: $2.50" << endl;
  cout << "4. Trail Mix: $1.50" << endl;
  cout << "5. Chocolate: $1" << endl;

  cout << "Enter you selection: " << flush;
  int input;
  cin >> input;


  if (input == 1) {
    cout << "You added Popcorn to your cart." << endl;
    float cost = 2;
    cout << "Your total is $" << cost << endl;
  }
  
  if (input == 2) {
    cout << "You added Coconut Clusters to your cart." << endl;
    float cost = 3;
    cout << "Your total is $" << cost << endl;
  }
  
  if (input == 3) {
    cout << "You added Granola Bar to your cart." << endl;
    float cost = 2.50;
    cout << "Your total is $" << cost << endl;
  }

  if (input == 4) {
    cout << "You added Trail Mix to your cart." << endl;
    float cost = 1.50;
    cout << "Your total is $" << cost << endl;
  }

  if (input == 5) {
    cout << "You added Chocolate to your cart." << endl;
    float cost = 1;
    cout << "Your total is $" << cost << endl;
  } 

  

  cout << "Pay amount: " << flush;
  float money;
  cin >> money;

  if (money > cost) {
    float change = money-cost;
    cout << "Thank you! You have $" << change << " change." << endl;
  }

  if (money == cost) {
    cout << "Thank you! Have a nice day!." << endl;
  }

  if (money < cost) {
    float amountOwed = cost-money;
    cout << "Please insert another $" << amountOwed << endl;

    cout << "Enter amount: " << flush;
    float payment;
    cin >> payment;

    if (payment > amountOwed) {
    float change2 = payment-cost;
    cout << "Thank you! You have $" << change2 << " change." << endl;
    }

    if (payment == amountOwed) {
      cout << "Thank you! Have a nice day!." << endl;
    }

    if (payment < amountOwed) {
      cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
    }

  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

And*_*zel 5

问题是您正在执行以下操作:

int main()
{
    [...]
    if (input == 1) {
        cout << "You added Popcorn to your cart." << endl;
        float cost = 2;
        cout << "Your total is $" << cost << endl;
    }
    [...]
    if (money > cost) {
        [...]
    }
    [...]
}
Run Code Online (Sandbox Code Playgroud)

变量的范围cost仅限于if块,因为那是您声明它的地方。因此,当您计算表达式时,该变量不再存在money > cost

要解决此问题,您应该改为cost在函数的主块范围内声明变量,如下所示:

int main()
{
    float cost;

    [...]
    if (input == 1) {
        cout << "You added Popcorn to your cart." << endl;
        cost = 2;
        cout << "Your total is $" << cost << endl;
    }
    [...]
    if (money > cost) {
        [...]
    }
    [...]
}
Run Code Online (Sandbox Code Playgroud)