您遇到的問題是雙重的。第一個,scanf
需要一個指針來存儲值。 (例如scanf ("%f", principal);
應該scanf ("%f", &principal);
)
另一個問題需要注意的是讀值隨scanf
每次按[Enter]
時會留下一個換行符'\n'
輸入緩衝區stdin
。 scanf
會讀取您輸入的號碼,但將換行符保留在stdin
。下次您撥打scanf
時,它會在stdin
中看到換行符(值:0xa
十六進制,10
),並將其作爲下一個值讀取。
注意:在這種情況下,%f
將跳過換行,所以這是沒有必要的。但是,請注意,由scanf
讀取的小數或字符串將會生效。在使用scanf
時請始終記住這一點。
如果遇到scanf
似乎會跳過預期的輸入,一個簡單的解決方案是清空(空)輸入緩衝區。 (下面的函數flush_stdin
提供瞭如何處理這個問題的一個例子)。在每次致電scanf
後,請致電flush_stdin
,這是潛在的問題。
#include <stdio.h>
// #include <conio.h>
void flush_stdin()
{
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
int main(void)
{
int year = 0; /* Always INITIALIZE your variables */
float principal, amount, inrate, period, value;
principal = amount = inrate = period = value = 0;
printf ("Please enter principal: ");
scanf ("%f", &principal);
amount = principal;
printf ("Please enter interest rate: ");
scanf ("%f", &inrate);
year = 0;
printf ("Please enter period: ");
scanf ("%f", &period);
while(year <= period)
{
printf ("%3d %10.2f\n", year, amount);
value = amount + amount*inrate;
year = year + 1;
amount = value;
}
// getch();
return 0;
}
輸出
$ ./bin/scanf_noop
Please enter principal: 123.45
Please enter interest rate: .05
Please enter period: 24
0 123.45
1 129.62
2 136.10
3 142.91
4 150.05
5 157.56
6 165.43
7 173.71
8 182.39
9 191.51
10 201.09
11 211.14
12 221.70
13 232.78
14 244.42
15 256.64
16 269.48
17 282.95
18 297.10
19 311.95
20 327.55
21 343.93
22 361.12
23 379.18
24 398.14
記住使用'&'和'scanf'。 – teppic 2015-04-04 19:28:47
感謝它的工作。 – SirVirgin 2015-04-04 19:31:22
用'-Wall'選項編譯。 – BLUEPIXY 2015-04-04 19:32:15