如何从if语句c ++中获取价值?

时间:2012-02-20 16:00:33

标签: c++ if-statement

如何从if语句中获取值?我的意思是如果数字大于151,就像在第一个if语句中一样。如何从该块中获取r1的值,因此我可以在最后添加所有内容,包括选择if语句的特定值。

int main (int argc, const char * argv[])
{
    const double beefMeal = 12.95;
    const double chickenMeal = 10.95;
    const double veganMeal = 8.95;
    int beef, chicken, vegan;
    const int room1 = 250;
    const int room2 = 200;
    const int room3 = 100;
    const int room4 = 50;
    int numParty;
    double r1= 0, r2= 0, r3= 0, r4= 0, b1, c1, v1;
    double grat, total;

    cout <<"Enter number of beef meals: ";
    cin>>beef;
    cout<<endl;
    cout <<"Enter number of chicken meals: ";
    cin>>chicken;
    cout<<endl;
    cout <<"Enter number of vegan meals: ";
    cin >> vegan;
    cout<<""<<endl;

    cout<<"A Caterers Program"<<endl;
    cout<<""<<endl;

    cout.setf (ios::fixed | ios::showpoint);
    cout.precision(2);
    cout<<"Number in party: ";
    cin>> numParty;
    if(numParty>151)
    {
        r1 = (room1 * 6.5)/100;
        cout<<"Room cost:                                           $"<<room1<<endl;
        cout<<"Room tax:                                            $"<<r1<<endl;
    }
    else
    {
        if (numParty <= 150 && numParty >= 100) 
        {
            r2 = (room2 * 6.5)/100;
            cout<<"Room cost:            $"<<room2<<endl;
            cout<<"Room tax:             $"<<r2<<endl;
        }
        else
        {
            if (numParty <= 99 && numParty >= 31)
            {
                r3 = (room3 * 6.5)/100;
                cout<<"Room cost:            $"<<room3<<endl;
                cout<<"Room tax:             $"<<r3<<endl;
            }
            else
            {
                if (numParty <= 30)
                {
                    r4 = (room4 * 6.5)/100;
                    cout<<"Room cost:            $"<<room4<<endl;
                    cout<<"Room tax:             $"<<r4<<endl;
                }
            }
        }
    }

    cout<<"Number of beef dinners:    "<<beef<<endl;
    b1 = beef * beefMeal; 
    cout<<"Cost of beef dinners:               $"<<b1<<endl;
    cout<<"Number of chicken dinners: "<<chicken<<endl;
    c1 = chicken * chickenMeal; 
    cout<<"Cost of chicken dinners:            $"<<c1<<endl;
    cout<<"Number of vegan dinners:   "<<vegan<<endl;
    v1 = vegan * veganMeal; 
    cout<<"Cost of vegan dinners:              $"<<v1<<endl;
    grat = (b1 + c1 + v1) * 0.18;
    cout<<"Food Gratuity:                      $"<<grat<<endl;

    cout<<"________________________________________________"<<endl;
    total = grat + v1 + c1 + b1 + r1 + r2 + r3 + r4;
    cout<<"Total: $"<< total;
}

2 个答案:

答案 0 :(得分:2)

由于您在最外层范围内声明了变量r1,r2...,因此它们是有效的,并且可以在外部范围内的任何范围内访问。

答案 1 :(得分:0)

您的代码是某个函数的主体,所有这些双变量都是该函数的局部变量,这意味着它们在其范围内可见。对此,您不需要做任何特殊的事情,只需确保它们已正确初始化和/或分配值。

void foo()
{
   double r1 = 0;

   if(some_condition)
   {
       // use r1...
   }
   else
   {
      // use r1...
   }

   // use r1...        
}