刚开始编码就被困在数学上了。代码应该在用户输入后执行一个加法运算,但我只在终端上运行代码时得到像-952492524这样的随机结果。正确的解决方法是什么?
这是代码:

#include <stdio.h>

main()
{
    int iquantity, iprice;
    int iresult = iquantity + iprice;

    scanf("%d", &iquantity);
    scanf("%d", &iprice);

    printf("%d", &iresult);
}

最佳答案

对printf的调用是打印变量的地址,而不是其值。scanf需要地址,因为它将更改变量的值;这是通过指针传递变量。
printf只需要读取值,因此参数是按值传递的,而不是按指针传递的。
这是用C编写代码时要学习的一个重要概念;与现代语言不同,C不隐藏变量引用:必须包含指针,并知道何时使用指针,何时不使用指针。
这是一个很好的链接,可以进一步了解这个主题。What's the difference between passing by reference vs. passing by value?
试试这个:

#include <stdio.h>

int main(void)
{

    int iquantity, iprice;

    scanf("%d", &iquantity);

    scanf("%d", &iprice);

    int iresult = iquantity + iprice; /* after scanf, not before */

    printf("%d", iresult); /* and don't need a reference here */
}

关于c - 在计算中获得随机结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43458882/

10-10 23:36