//0、1、1、2、3、5、8、13、21、34
//F(0) = 0,F(1) = 1, F(n) = F(n - 1) F(n - 2)(n >= 2,n∈N*)
#include <stdio.h>
int Fibonacci(int n);
int get_int(void);
int main(void)
{
int n, i;
printf("Please enter the No. (<0 to quit) :\n");
n = get_int();
while (scanf("%d", &n) == 1 && n > 0)
{
for (i = 1; i <= n; i )
{
printf("%d ", Fibonacci(i));
}
printf("\n");
}
printf("Done.\n");
return 0;
}
int Fibonacci(int n)
{
if (n == 1)
{
return 0;
}
else if (n == 2)
{
return 1;
}
else if (n >= 3)
{
return Fibonacci(n - 1) Fibonacci(n - 2);
}
}
int get_int(void)
{
int x;
while (scanf("%d", &x) != 1)
{
scanf("%*s");
printf("Please enter an integer number(>0):\n");
}
while (getchar() != '\n')
continue;
return x;
}
input & output 在此處輸入影像描述 正如您在圖片中看到的,當我第一次輸入 8 時,它不運行任何東西。只有再次輸入8,它才能順利運行。如何修改代碼,以便在我第一次輸入 8 時可以列印?
謝謝,只是一個新手。我修改如下:
//F(0) = 0,F(1) = 1, F(n) = F(n - 1) F(n - 2)(n >= 2,n∈N*)
#include <stdio.h>
int Fibonacci(int n);
int get_int(void);
int main(void)
{
int n, i;
printf("Please enter the No. (<0 to quit) :\n");
n = get_int();
while (n > 0)
{
for (i = 1; i <= n; i )
{
printf("%d ", Fibonacci(i));
}
printf("\n");
}
printf("Done.\n");
return 0;
}
int Fibonacci(int n)
{
if (n == 1)
{
return 0;
}
else if (n == 2)
{
return 1;
}
else if (n >= 3)
{
return Fibonacci(n - 1) Fibonacci(n - 2);
}
}
int get_int(void)
{
int x;
while ((scanf("%d", &x)) != 1)
{
scanf("%*s");
printf("Please enter an integer number(>0):\n");
}
while (getchar() != '\n')
continue;
return x;
}
之前的問題已經解決了。然而,一個新的問題出現了: 這里輸入圖片描述
輸出并沒有停止。有什么問題?
uj5u.com熱心網友回復:
你宣告:n = get_int();它呼叫get_int(). 在get_int()您詢問您的用戶輸入(by scanf("%*s");)時,如下所示:
int get_int(void)
{
int x;
while (scanf("%d", &x) != 1)
{
scanf("%*s"); // <-- you ask for user input in this line.
printf("Please enter an integer number(>0):\n");
}
while (getchar() != '\n')
continue;
return x;
}
然后,您撥打scanf()的main()在這里看到:
int main(void)
{
int n, i;
printf("Please enter the No. (<0 to quit) :\n");
n = get_int();
while (scanf("%d", &n) /* <-- here */ == 1 && n > 0)
{
for (i = 1; i <= n; i )
{
printf("%d ", Fibonacci(i));
}
printf("\n");
}
printf("Done.\n");
return 0;
}
所以你要求用戶輸入 2 次,這會導致你的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327473.html
標籤:C
上一篇:在多線性陣列周圍添加一行和一列
下一篇:我應該如何在C中制作這個邏輯?
