2012-11-12 18 views
0
#include <stdio.h> 
#include <conio.h> 

int main() 
{ 
float L=0; //L is litre 
float gallon; 
gallon = 3.785*L; 
char input; 
float cost; 

printf("Hello, welcome to PetrolUpHere!!\n"); 
printf("Would u like unleaded or diesel fuel?"); 
scanf("%c", &input); 
printf("Enter the litre you want to fuel:"); 
scanf("%f", &L); 

switch (input) { 
case 'u' : 
cost = 1.98*gallon; 
printf("The cost is :%f ",&cost); 
break; 

case 'd' : 
cost = 1.29*gallon; 
printf("The cost is :%f ",&cost); 
break; 
} 

getch(); 
return 0; 
} 

程序不能顯示成本結果,並且在完成輸入scanf語句和L值後,僅顯示成本= 0.0000。我,新的C程序和希望可以得到幫助。謝謝c-cant printf成本

+0

添加一個換行符可以解決它。否則,輸出緩衝區不會刷新。您也可以手動調用'fflush'。 –

+0

使用二進制浮點類型(如float)計算貨幣金額不是一個好主意。貨幣計算的四捨五入是根據涉及十進制表示的精確規則來定義的。 –

回答

1

你已經多次做了L到計算加侖

float L=0; //L is litre 
float gallon; 
gallon = 3.785*L; //here gallon is zero already 

所以你probebaly得到

printf("The cost is :%f ",&cost); 

出把he cost is :address

所以儘量

gallon = 3.785*L; // try this here 
switch (input) { 

printf("The cost is :%f ", cost); 
1

,我認爲這就是問題所在,每加侖爲0:

float L=0; //L is litre 
gallon = 3.785*L; 

你應該多後您的閱讀升:

float L=0; //L is litre 
float gallon=3.785f; 
... 
//read liters 
scanf("%f", &L); 
... 
cost = 1.98f*gallon*L; 
0

您需要2改變

gallon = 3.785*L; 

需要b e移到所有的下方scanfs

第二個改變是打印cost而不是&cost

1

有了這行代碼:

float my_var; 
printf("Hi %f", &my_var); 

您將打印地址my_var,即:它存儲在內存中。不是變量的值。我想你會感到困惑,因爲你的scanf需要一個指向你想要更新的值被存儲在哪裏的指針。對指針進行一些閱讀,它會更清晰一些。現在的解決方法是改變你的printf語句是這樣的:

float my_var; 
printf("Hi %f", my_var); 

此外,需要你加侖線從用戶的所有輸入後移動,否則你會被0時開始只是乘以該計劃將保持爲零而不是預期的結果。

0

您應該寫出「加侖= 3.785 * L」的聲明。從用戶讀取L之後,其他明智加侖將變爲零,因爲L初始化爲零。因此成本的值也變爲零。

並從printf語句中刪除'&'。 這次肯定會工作。