这是我的代码。
#include <stdio.h>
/*
Write a C program that accepts two integers from the user then outputs the sum, difference, product, and division of the two integers.
*/
float main()
{
float x, y; //defining input variables and the output/answer
printf("Input the first number: %f", x); //user inputs 1st number
scanf("%f", &x);
printf("Input the second number: %f", y); //user inputs 2nd number
scanf("%f", &y);
printf("\n");
//math
float sum = x + y;
float diff = x - y;
float product = x * y;
float div = x / y;
//outputting the math
printf("The sum is: %.2f\n", sum);
printf("The difference is: %.2f\n", diff);
printf("The product is: %.2f\n", product);
printf("The division is: %.2f\n", div);
return 0.0;
}
是的,我确实希望它是浮点变量而不是整数变量,这样它才能更准确地计算除法。这样做可以避免输出 2/3 = 0。
4
最佳答案
1
main()
通常会返回一个int
。float x, y
尚未初始化,并且打印不确定的值是无用的。- 始终检查返回值,
scanf()
否则您的变量可能会不确定。 - (不固定)
double
优于float
。 - (未修复)C 2023 6.5.5 §6 规定“如果第二个操作数的值为零,则行为未定义。”但它是有效的 IEEE 754 数字,即 -Inf 或 +Inf。如果这不适合您,请在除法之前添加 guard if。
#include <stdio.h>
int main() {
float x;
printf("Input the first number: ");
if(scanf("%f", &x) != 1) {
printf("scanf failed\n");
return 1;
}
float y;
printf("Input the second number: ");
if(scanf("%f", &y) != 1) {
printf("scanf failed\n");
return 1;
}
printf("\n");
float sum = x + y;
printf("The sum is: %.2f\n", sum);
float diff = x - y;
printf("The difference is: %.2f\n", diff);
float product = x * y;
printf("The product is: %.2f\n", product);
float div = x / y;
printf("The division is: %.2f\n", div);
}
示例运行:
Input the first number: 2
Input the second number: 3
The sum is: 5.00
The difference is: -1.00
The product is: 6.00
The division is: 0.67
18
-
关于“打印未初始化的变量是未定义行为”:不是。未初始化的对象具有不确定的值,并且,如果在此代码中插入了打印它们的调用,则 C 标准会将它们定义为打印该
float
类型的一些有效值。
– -
@EricPostpischil 另有说法。
–
-
2不同意,
if(fabs(y) > if(fabs(y) > 1e-10))
因为1e-10
完全是任意的。if(y != 0.0)
有一定的道理。
–
-
@chux-ReinstateMonica 是的,只是当我尝试使用 0 时得到了 Inf,而且我不确定标准是否保证了这一点。我的确想回滚代码更改。
–
-
1@AllanWind:正如我所写,这是一个总结。它掩盖了细节,在这种情况下省略了技术条件。而且它是非规范性的,正如附件 J 的标题所述,这意味着它不是定义一致性的标准的一部分。标准主要部分中的任何内容都会覆盖附件 J。在这一点上它是错误的,主要标准是正确的。
–
|
float main()
相当不寻常。是谁提出这个建议的?–
printf("Input the first number: %f", x);
非常奇怪;为什么在输入之前要打印它,为什么会对输出的值感到困扰——根据编译器、标志,甚至是星期几,输出可能是0.000
,42.424242e42
或者只是一次可怕的崩溃。–
–
–
|