0

在这段代码中,我试图让用户输入一个 int 值 (x),然后在下面的 while 循环中比较这个值:while(k < x)。当我这样做时,我的程序崩溃了。

int main()
{
    long int sum = 0;
    long int i = 1;
    long int j = 2;
    long int k = 0;
    int x = 0;
    printf("This program will sum up all of the evenly valued terms from the 
    Fibionacci sequence, up until the\n user-specified highest term value.\n");
    printf("Set this limit: "); 
    scanf("%d",x);

while(k < x)
{   
    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 Fibionacci sequence up     until the value %d is %d",x,sum);
return 0;
}
4

2 回答 2

5

你的程序因为这一行而崩溃:

scanf("%d",x);

C 通过传递参数,而不是通过引用。因此,对于能够从调用者修改变量的 C 函数,该函数需要一个指针,并且调用者必须传递变量的地址:

scanf("%d", &x);

通过忽略传递地址,scanf尝试写入内存中的某个任意位置(在本例中为地址 0),这会导致未定义的行为。

另请参阅comp.lang.c FAQ 中的 Q12.12

于 2013-03-17T04:55:34.123 回答
3

这里需要一个地址:

scanf("%d",x); // ==> scanf("%d", &x);

否则会发生奇怪的事情。在 C 中,当您期望在函数参数中接收结果时,您传递了一个地址。

于 2013-03-17T04:53:34.380 回答