-5

これは私がターボ 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

中括弧が間違っているため、後の最初の行のみが中括弧に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"] = ....;

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;
}
于 2013-01-23T12:49:29.680 に答える
1

ブレースが間違った場所にあります。

中かっこは、ifブロックまたはelseブロックに対して使用され、if または else ブロックの前には使用されません。

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 に答える