我正在尝试制作一个程序,允许用户发现斐波那契数列中偶数项的总和,直至任意的、用户定义的长度。我这样做是为了让用户有机会进行新的计算(如果他们选择的话)。我使用 bool 逻辑和 while 循环来实现某种程序重新启动。
程序第一次执行得很好。然而,对于每个后续的用户输入,前一个答案都会影响当前的答案。我尝试在 while 循环开始时将变量重新初始化为其初始值(i = 1、j = 2、k = 0 和 sum = 0),但它仍然没有给我想要的结果。感谢您的帮助。
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main()
{
bool stayAlive = true;
long int sum = 0; //The sum of all even Fibonacci numbers
long int i = 1; //initial 1st value of the Fibonacci sequence
long int j = 2; //initial 2nd value of the Fibonacci sequence
long int k = 0; //initial 3rd value of the Fibonacci sequence
int x = 0;
char name[50];
printf("Hello, may I have your name?\n\n");
scanf("%s", &name);
putchar('\n');
while(stayAlive)
{
printf("Hello %s! This program will sum up all of the evenly valued terms from\nthe Fibonacci sequence, up until an upper limit term specified by the user.\n",name);
printf("Set this limit: ");
scanf("%d",&x);
putchar('\n');
char c;
while(k < x)//WHILE the "last term" is LESS than the "max term"
{
i ==1;
j ==2;
k ==0;
sum ==0;
k = i + j;
if(k%2==0)
sum +=k;
i = j;
j = k;
}
printf("The sum of all of the evenly valued terms of the Fibonacci sequence up until\nthe value %d is %d.",x,sum); puts("\n");
printf("Try another calculation? (Y/N) ");
scanf("%s", &c);
if(c == 'y'|| c == 'Y')
continue;
else
printf("\nThanks for using this program, %s!",name);//This name character is not outputting here, even though it outputs earlier
getchar();
break;
}
return 0;
}
最佳答案
当你想要:
reinitialize my variables to their initial values (i = 1, j = 2, k = 0, and sum = 0) at the beginning of the while loop
放置:
sum = 0;
i = 1;
j = 2;
k = 0;
在 while 循环内。
同时删除这些行:
i ==1;
j ==2;
k ==0;
sum ==0;
另外,您可以使用 %c 代替:
scanf("%c", &c);
因为您只阅读一个字符。
关于c - 在 C 中,我使用 bool 逻辑通过 while 循环转到程序的开头,但是在我告诉它们之后,我的变量没有重新初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15458655/