c ++ /加油站或汽油泵程序

时间:2013-01-23 12:46:38

标签: c++

这是我用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卢比(英寸)/升,柴油是48 //

3 个答案:

答案 0 :(得分:4)

你的大括号错了,所以只有if之后的第一行才绑定它。试试这个:

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;
}

如果您想将此概括为其他类型的燃料,您可以使用std::map<std::string, double>匹配的燃料类型字符串来定价:

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

然后,将燃料类型读入tring而不是char

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

然后您可以检查燃料类型是否在地图中,并采取措施:

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;
}

答案 1 :(得分:1)

牙箍在错误的地方。

括号来自if块或else块,而不是if或else块。

if(petrol)
{
//petrol - no of litres calculation
}
else if(diesel)
{
//diesel- no of litres calculation
}

答案 2 :(得分:-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
}