2017-03-04 28 views
-1

該代碼應該打印輸入內容的精確值並保留2個小數位,但不管打印什麼數字正在輸入。令人驚訝的是,名稱打印完美,但打印的(有序數量)值將始終爲零,並帶有2位小數位。可以請任何人告訴我出了什麼問題?是的,我仍然是這個初學者。無論輸入的是多少個數值,都有一個0.00浮點值的輸出

#include<stdio.h> 
#include<string.h> 

struct customer 
{ char customer_name[20]; 
    float order_amount; 
}c[10]; 

int main() 
{ int i; 

    clrscr(); 

    printf("\n******Enter customer details******\n"); 

    for(i=0; i<10; ++i) 
    { 
     printf("\nEnter customer name: "); 
     fflush(stdin); 
     gets(c[i].customer_name); 
     printf("Enter order amount: "); 
     scanf(" %0.2f",&c[i].order_amount); 
    } 

    printf("\n\t*********Displaying information*********\n"); 
    printf("\nCustomers that has ordered are: \n"); 

    for(i=0; i<10; ++i) 
    { printf("\nCustomer name: %s\n",c[i].customer_name);  
     printf("Ordered amount: %0.2f\n",c[i].order_amount); 
    } 
    return 0; 
} 

謝謝。

+2

不要使用'得到()'。永遠。緩衝區溢出會困擾你。 – Siguza

+2

'fflush(stdin);'調用*未定義的行爲*和'gets()',具有不可避免的緩衝區溢出風險,已在C99中棄用並從C11中刪除。 Wild code ... – MikeCAT

+1

您是否介意發佈用於測試的輸入數據? – MikeCAT

回答

1

您在scanf中添加了一個空格。應該是scanf(「%s」,...)以及scanf(「%f」,...)而不是scanf(「%s」,....)都不是scanf(「%f」,.. )

1

首先,使用格式執行scanf無法正常工作。不確定它做什麼,但讀取浮動數據完全沒用。只需使用%f,沒有空間,並且浮標將被讀取。

假如你檢查scanf返回代碼,你會看到,它返回0而不是1

然後,有利於保護scanf的下降gets以避免緩衝區溢出。

低於代碼工作正常:

#include<stdio.h> 
#include<string.h> 

struct customer 
{ char customer_name[20]; 
    float order_amount; 
}c[10]; 

int main() 
{ int i; 
    int n=10;  

    printf("\n******Enter customer details******\n"); 

    for(i=0; i<n; i++) 
    { 
     printf("\nEnter customer name: "); 
     scanf("%19s",c[i].customer_name); // not above 19 characters 
     printf("Enter order amount: ");   
     scanf("%f",&(c[i].order_amount)); // plain scanf %f 
    } 
    // print routine is unchanged 

    printf("\n\t*********Displaying information*********\n"); 
    printf("\nCustomers that has ordered are: \n"); 

    for(i=0; i<n; ++i) 
    { printf("\nCustomer name: %s\n",c[i].customer_name);  
     printf("Ordered amount: %0.2f\n",c[i].order_amount); 
    } 
    return 0; 
} 
+0

但是那麼說scanf:浮點格式不能鏈接 – JustABeginner

+0

什麼時候?編譯時?哪一行?請更具體。在gcc上工作 –

相關問題