//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 enter image description here As you can see in the picture, when I first enter 8. It does not run anything. Only if I enter 8 again, it could run smoothly. How to modify the code so that when I first enter 8 it could print?
Thanks, justANewbie. I have modified as followsing:
//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;
}
The question before has been solved. However, a new problem arises like this: enter image description here
The output hasn't stop. What's the problem?
CodePudding user response:
You declare: n = get_int();
which calls get_int()
. In get_int()
you ask your user input(by scanf("%*s");
) as seen in here:
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;
}
Then, you call scanf()
in main()
as seen in here:
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;
}
So you ask for user input 2 times and that cause your error.