我正在尝试制作一个程序,该程序允许用户发现斐波那契数列中偶数项的总和,直至任意用户定义的长度。我这样做是为了让用户有机会在他们选择时进行新的计算。我正在使用布尔逻辑和 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;
}