簡體   English   中英

為什么我的浮點數打印為0,即使我使用scanf輸入13.5?

[英]Why does my float print out as 0 even though I input 13.5 for it using scanf?

我無法弄清楚為什么我的浮點變量在輸入數字時保持打印輸出為0。

碼:

int num, month, day, year;
float price[10000];


printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price);
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);

printf("Item\t\tUnit\t\tPurchase\n");
printf("    \t\tPrice\t\tDate\n");
printf("%d      ", num);
printf("$%.2f     ", price); 
printf("      %d/%d/%d\n", month, day, year);
return 0;

我為我的商品編號輸入555,為我的價格輸入13.5,為我的日期輸入10/24/2010。 當我這樣做時打印出我的價格是0.00美元。 它為我輸入的任何數字執行此操作。 為什么?

你不能像這樣插入數組值 -

scanf("%f", &price);

使用for循環將值插入數組價格 -

for(i=0; i<sizeWhatYouWant; i++){
 scanf("%f", &price[i]);
}

或者只是將申報float price[10000]更改為 -

float price;

只需改變這個:

float price[10000];

對此:

float price;

因為您將它用作單個變量而不是數組

您已將price聲明為您需要這樣做的數組

int num, month, day, year;
float price[10000];


printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price[0]); /* <---- it's not &price it's &price[0] */
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);

printf("Item\t\tUnit\t\tPurchase\n");
printf("    \t\tPrice\t\tDate\n");
printf("%d      ", num);
printf("$%.2f     ", price[0]); /* <---- it's not price it's price[0] */
printf("      %d/%d/%d\n", month, day, year);
return 0;

你必須將值存儲在數組的第一個元素中,然后打印第一個元素,即price[0]

如果您只想讀取單個值,那么您不需要將price聲明為數組,因此這將是解決方案

int num, month, day, year;
float price/* [10000] it doesn't need to be an array */;

printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price);
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);

printf("Item\t\tUnit\t\tPurchase\n");
printf("    \t\tPrice\t\tDate\n");
printf("%d      ", num);
printf("$%.2f     ", price);
printf("      %d/%d/%d\n", month, day, year);
return 0;

您正在將地址打印到數組的第一個元素而不是該地址的值,並且它被轉換為unsigned intunsigned long int ,因此當您使用"%f"說明符時,它打印為0

在這兩種情況下

為了防止出現這種錯誤,如果使用gcc ,你應該打開你的編譯器警告

gcc -Wall -Wextra -Werror ${SOURCE_FILES} -o ${OUTPUT_FILE}

會做的。

而且,在無效輸入時,您的程序將具有未定義的行為,您需要檢查scanf()確實讀取了您指示它讀取的值,這是通過檢查scanf()的返回值來實現的,該值等於匹配的項目,在您的情況下

if (scanf("%d", num) != 1)
    errorInputWasInvalid();

因為您要請求1項目,所以scanf()必須返回1

有兩件事需要注意。

  1. 改變float price[10000]; float price; 因為你只使用一個float變量,所以你不需要一個數組。

  2. 您需要檢查scanf()的返回值以確保正確輸入。

另外,作為注釋,您可能希望初始化局部變量,因為它們不會自動初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM