在这段代码中,我试图让用户输入一个 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;
}
最佳答案
你的程序因为这一行而崩溃:
scanf("%d",x);
C 通过值 传递参数,而不是通过引用。因此,对于能够从调用者修改变量的 C 函数,该函数需要一个指针,并且调用者必须传递变量的地址:
scanf("%d", &x);
通过忽略传递地址,scanf
尝试写入内存中的某个任意位置(在本例中为地址 0),这会导致未定义的行为。
关于c - 在 C while 循环中,是否可以比较两个变量 while (a < b)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15457650/