2013-01-23 33 views
-4

這是我在turbo C++中編寫過的程序,基本上我已經說過它來計算購買特定數量的汽油或柴油的公升;問題是它沒有單獨顯示汽油和柴油,請運行它並告訴我我做了什麼錯誤?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 //

+0

你是什麼意思,「它不是單獨顯示汽油和柴油」 –

+2

檢查你的{}。他們追求如果。 –

+0

你有沒有聽說過縮進? – rburny

回答

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

,你cound使用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; 
} 
+0

非常感謝您的幫助,謝謝您的幫助,但是如果我必須添加1個其他東西,如CNG或其他東西,以顯示不同的CNG,那麼我必須使用if或else if? – aki

+0

@aki我使用'std :: map'添加了一個解決方案。 – juanchopanza

1

大括號在錯誤的地方。

花括號爲if塊或else塊,不在if或else之前。

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

我還沒有跑,因爲我目前沒有檢查的位置。我不知道,如果「渦輪」 C++有不同的語法,但你的「如果」語句有「{」在錯誤的地方(開放範圍)和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 
}