-5

这是我用 turbo c++ 编写的程序,基本上我已经用它来计算以特定数量购买的汽油或柴油升数;问题是它没有单独显示汽油和柴油,请运行它并告诉我我做错了什么?

#include<iostream.h>
#include<conio.h>

void main()
{
    clrscr();
    double amount,res;
    char ch;
    cout<<"Welcome to Bharat Petroleum"<<endl;
    cout<<"Press P for Petrol and D for Diesel:"<<endl;
    cin>>ch;
    {
        if (ch=='P')
            cout<<"Enter your Amount:"<<endl;
        cin>>amount;
        res=(amount/68)*1;
        cout<<"Petrol purchased in litres:"<<endl<<res;
    }
    {
        if (ch=='D')
            cout<<"Enter your Amount:"<<endl;
        cin>>amount;
        res=(amount/48)*1;
        cout<<"Diesel purchased in litres:"<<endl<<res;
    }
    getch();
}

// 其中汽油是 68 卢比 (inr)/升,柴油是 48//

4

3 回答 3

4

Your braces are wrong, so only the first line after the if is bound to it. Try this:

if (ch=='P')
{
  cout<<"Enter your Amount:"<<endl;
  cin>>amount;
  res=(amount/68)*1;
  cout<<"Petrol purchased in litres:"<<endl<<res;
} 
else if (ch=='D')
{
  cout<<"Enter your Amount:"<<endl;
  cin>>amount;
  res=(amount/48)*1;
  cout<<"Diesel purchased in litres:"<<endl<<res;
}

If you want to generalize this to other types of fuel, you cound use an std::map<std::string, double> matching fuel type strings to prices:

std::map <std::string, double fuelPrices;
fuelPrices["P"] = 68.;
fuelPrices["D"] = 48.;
fuelPrices["CNG"] = ....;

Then, read the fuel type into a tring instead of a char:

std::string fuel;
....
cin >> fuel;

Then you can check if the fuel type is in the map, and take action:

if (fuelPrices.find(fuel) != fuelPrices.end())
{
  // fuel is in map
  cout<<"Enter your Amount:"<<endl;
  cin>>amount;
  double res=(amount/fuelPrices[fuel])*1;
  cout<< fuel << " purchased in litres:"<<endl<<res;
}
于 2013-01-23T12:49:29.680 回答
1

The braces are at wrong places.

The braces come for the if block or else block and not before the if or elseblock.

if(petrol)
{
//petrol - no of litres calculation
}
else if(diesel)
{
//diesel- no of litres calculation
}
于 2013-01-23T12:51:02.040 回答
-1

我没有运行它,因为我目前无法检查。我不确定'turbo' c++ 是否有不同的语法,但你的'if'语句在错误的地方有'{'(开放范围),应该在if语句之后的行:

{
    if (ch=='P')
          blah; // only this will be done if the statement is true
    ...
}

应该:

if (ch=='P')
{
    ...  //Now all of the code int eh brackets will be done if the if statement is true
}
于 2013-01-23T12:53:07.270 回答