这是我的代码。

#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

  • 8
    float main()相当不寻常。是谁提出这个建议的?


    – 


  • 2
    printf("Input the first number: %f", x);非常奇怪;为什么在输入之前要打印它,为什么会对输出的值感到困扰——根据编译器、标志,甚至是星期几,输出可能是0.00042.424242e42或者只是一次可怕的崩溃。


    – 


  • 3
    。您的代码在用户输入之前未给 x 和 y 赋任何值。有几个原因可能导致它们一开始看起来是那样,但这并不能保证,您不能依赖它。您真的不应该在它们正确建立之前尝试使用它们的值。


    – 


  • 2
    这个问题类似于:。如果您认为它有所不同,请编辑问题,说明它有何不同和/或该问题的答案对您的问题无益。


    – 


最佳答案
1

  1. main()通常会返回一个int
  2. float x, y尚未初始化,并且打印不确定的值是无用的。
  3. 始终检查返回值,scanf()否则您的变量可能会不确定。
  4. (不固定)double优于float
  5. (未修复)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。在这一点上它是错误的,主要标准是正确的。


    –