[英]C Programming: Scanf in while loop only reads input once and then terminates
[英]C programming - While loop and scanf
誰能告訴我為什么我的scanf
函數只能工作一次並且以連續循環結束。
#include <stdio.h>
#include <conio.h>
int main(void)
{
int accno;
float bbal, charge, rebate, limit, balance;
printf("Enter account number (-1 to end):");
scanf("%d", &accno);
while (accno != -1) // User input phase
{
printf("Enter beginning balance:"); // User input phase
scanf(" %.2f ", &bbal); // leave space after scanf("
printf("Enter total charges:");
scanf(" %.2f ", &charge);
printf("Enter total rebates:");
scanf(" %.2f ", &rebate);
printf("Enter credit limit:");
scanf(" %.2f ", &limit);
balance = bbal - charge + rebate;
// credit limit exceeded phase
if (balance > limit)
{
printf("Account: %u", accno);
printf("Credit limit: %.2f", limit);
balance = bbal - charge + rebate;
printf("Balance: %.2f", balance);
printf("Credit limit exceeded!");
}
printf("Enter account number (-1 to end):");
scanf("%d", &accno);
}
getch();
}
請改用scanf("%f", &variable)
。
看看scanf參考 。 長度( %.2
)子說明符對float(f)類型沒有意義。 因為scanf
將其解釋為未知的說明符並立即退出。
如果你不想限制scanf
占用的字符數量(這不是一個好主意,因為它可能會在stdin
留下一些字符並弄亂下一個scanf
調用),你可以使用寬度子說明符%2f
。
另一方面, printf
與浮動的子指定符完全沒問題。 代碼printf("%.2f", variable)
將打印精度為2位小數的浮點數。 我想你是在混淆它們。
始終檢查scanf
掃描了所有項目。
if(scanf("%d %d %d", &my_int1, &my_int2, &my_int3) != 3) { puts("scanf failed to scan all items!"); return EXIT_FAILURE; }
if(scanf("%d %d %d", &my_int1, &my_int2, &my_int3) != 3) { puts("scanf failed to scan all items!"); return EXIT_FAILURE; }
\\
不要在scanf
格式字符串中使用尾部和前導空格,除非您要跳過getc
函數的所有空格。
當我嘗試編譯問題中的代碼時,我收到一條警告,即scanf格式字符串%.2f
是非法的。 如果我將其更改為%f
(也需要刪除前導和尾隨空格),它將按預期開始工作。 我在Mac上使用clang,但它應該與Windows相同。
/Users/jeremyp/dev/foo/foo.m:19:18: warning: invalid conversion specifier '.' [-Wformat-invalid-specifier]
scanf(" %.2f ", &charge);
~~^
無論如何,正如其中一條評論所述,貨幣不是浮點數。 存儲貨幣的方法有很多種,最好的是大整數類型,例如64位的int,但是以美分或便士存儲貨幣,或者以您選擇的最低貨幣單位存儲。
在scanf("%.2f",&charge);
他們不應該是任何空間。 刪除所有間距。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.