Home  >  Q&A  >  body text

c++ - 最简单的两个数相加的程序,online judge为什么通不过?

题目是输入两个正整数,输出他们的和。输入的数在1(含)到10^6(含)之间。
scanfprintf就所有的测试用例都能通过,用cincout的话就总是有两个测试用例是wrong answer?但是实在看不出有什么问题。。
scanf的代码:

    double a, b;
    scanf("%lf %lf",&a,&b);
    printf("%.0lf", a + b);

cin,cout的代码:

    double x, y;
    cin >> x >> y;
    cout << x + y;

请问是哪儿可能导致这两种写法有不同的结果?

PHPzPHPz2766 days ago737

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 13:02:15

    Because results exceeding one million will be output by cout in scientific notation, so some cases cannot pass.
    Using double instead of int, although it does waste memory, does not cause errors due to precision when only adding positive integers.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:02:15

    If both numbers are positive integers, the output number must also be an integer. If the meaning of the question has been explained clearly, there is no need to use double

    reply
    0
  • 阿神

    阿神2017-04-17 13:02:15

    You can just change it to integers. I don’t understand why you need to use floating point numbers. Floating point numbers are related to precision and are prone to errors.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:02:15

    Is there a rounding error after adding some large numbers to floating point, causing the result to be xxx.00000001 or something like that?
    Since the description of using integers also gives a range, then use the ordinary int type to get everything now Int on mainstream platforms is at least 32-bit

    reply
    0
  • Cancelreply