gpt4 book ai didi

c - 为什么我得到 0 而不是 C 中计算 x - y 和 x/y 的结果

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:11 25 4
gpt4 key购买 nike

在这段代码中,我以为我会得到计算 x/y 和 x - y 的结果,但程序显示 i 和 j 为 0。怎么了?

#include <stdio.h>

float calculate(float, float);
float i, j;

int main()
{
float a, b;

printf("Enter two numbers:\n");
scanf("%f%f", &a, &b);
printf("\nThe results are: %f %f %f\n", calculate(a, b), i, j);

return 0;
}

float calculate(float x, float y)
{
float r;

r = x * y;
i = x / y;
j = x - y;
return r;
}

最佳答案

这是未定义的行为,当您在同一 printf 中调用 calculate() 函数时,i 和 j 是在该 printf(同一函数)中计算的。顺便说一句,使用全局变量 ( i, j ) 不是一个好主意......仅出于测试目的,您可以在 i 和 j 的下一个 printf 之前计算()。

您可以使用以下方法测试该行为:

#include <stdio.h>

float calculate(float, float);
float i, j;
int main()
{
float a, b;

printf("Enter two numbers:\n");
scanf("%f%f", &a, &b);
printf("\nThe results are: %f", calculate(a, b));
printf(" %f %f\n", i, j);

return 0;
}

float calculate(float x, float y)
{
float r;

r = x * y;
i = x / y;
j = x - y;
return r;
}

关于c - 为什么我得到 0 而不是 C 中计算 x - y 和 x/y 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53660563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com