在C while循环中,是否可以比较两个变量,而(a< b)?

时间:2013-03-17 04:51:45

标签: c while-loop comparison

在这段代码中,我试图让用户输入一个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;
}

2 个答案:

答案 0 :(得分:5)

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

scanf("%d",x);

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

scanf("%d", &x);

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

另见Q12.12 from the comp.lang.c FAQ

答案 1 :(得分:3)

您需要一个地址:

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

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