所以这可能是一个简单的修复,但我似乎无法弄明白。
用户输入
N
输入一个号码。 然后用户输入F以将斐波那契序列打印到该数字。
我的原始印刷品0-20(工作代码)被注释掉了。我尝试以相同的方式设置斐波纳契,但在打印数字时会得到垃圾。我现在已将它设置为在for循环之前暂停的位置,以便我可以看到它正在获得的数字。
#include <stdio.h>
char menu();
int read_int(int number);
void display(int answer);
int main(int argc, char ** argv) {
int number = 0;
char choice = 'O';
while (choice != 'X'){
choice = menu();
if (choice != 'N' && choice != 'F' && choice != 'X') {
printf("Invalid Input. Enter N, F, or X\n");
}
else if (choice == 'N') {
number = read_int(number);
printf("\nNumber equals: ");
printf("%d", number);
}
else if (choice == 'F') {
//printf("\nNumber equals: ");
//printf("%d", number);
display(number);
}
}
}
char menu ()
{
char i;
printf("\nEnter N to enter an integer from 0 to 20\nEnter F to display the first N+1 numbers (beginning with zero) on the console \nEnter X to quit the program \n");
printf("Your Choice: ");
scanf("%s", &i);
return i;
}
int read_int(int number)
{
number = 0;
printf("\nEnter an integer 0-20: ");
scanf("%d", &number);
if (number >=0 && number <=20)
return number;
else{
printf("Enter a valid number between 0 and 20");
return read_int(number);
}
}
void display(int answer)
{
// int count = 0;
// //printf("\nNumber equals: ");
// //printf("%d", answer);
// //int toprint = answer;
// while (count <= answer){
// printf("%d",count);
// printf(" , ");
// count=count+1;
//int n = answer;
int n = 0;
n = answer;
int first = 0, second = 1, next, c;
//printf("Enter the number of terms\n");
printf("\nNumber equals: ");
printf("%d", &answer);
scanf("%d",&n);
for ( c = 0 ; c < answer ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
//return 0;
}
答案 0 :(得分:4)
在您的情况下,问题是从
创建的 scanf("%s", &i);
%s
需要指向char
数组的指针,而不是单个char
元素。即使是单个char
输入,也会产生内存溢出,导致undefined behaviour。
您可以用
替换它 scanf(" %c", &i);
另外,printf("%d", &answer);
看起来不对,我想你并不是说&
会在那里。