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

标签 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;
}

最佳答案

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

scanf("%d",x);

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

scanf("%d", &x);

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

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

关于c - 在 C while 循环中,是否可以比较两个变量 while (a < b)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15457650/

相关文章:

c++ - 复制非矩形 roi opencv

c - 仅让两个进程在 MPI 中执行代码 - 虽然不知道哪些进程将进入代码段

python - 比较本地文件与远程文件

C语言-无法检查getchar()是字母还是数字

C++:指针值更改退出函数

java - 如何强制程序始终运行 while 循环的第一次迭代?

java - 如何从 Java 中的 while 循环返回 count 的值

python - 查找列表中连续项目的索引

string - JPA 字符串比较

Java字符串比较与正则表达式的区别?