c - 在 C 中,我使用 bool 逻辑通过 while 循环转到程序的开头,但是在我告诉它们之后,我的变量没有重新初始化

标签 c while-loop initialization boolean-logic

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

相关文章:

c - 将 int 分配给数组元素时出现段错误

mysql - 如何在函数中循环 MYSQL 查询/也许?

python - 使用 `is (CustomClass)` 可以安全地检测 Python 中的未初始化值

C++ vector 初始化

C++:如何使用初始化列表初始化内部结构的成员?

c - 返回结构并保存在不同 .c 文件中的结构变量中

c - 二维数组: C Programming

C 编程,在函数中更改字符串值而不将大小作为参数传递

python - 我有一个 while 循环用于一个由于某种原因无法运行的游戏

java - 没有额外的 readLine() 循环就无法检测到断开连接