当我在 codechef 中遇到错误答案时该怎么办

时间:2021-01-29 12:25:31

标签: c++ c debugging error-handling runtime-error

我在 CodeChef 中发现了一个问题,它要求我们编写一个程序来计算 T 测试用例 (1 ≤ T ≤ 1000) 的数字 N(1 ≤ N ≤ 1000000) 的第一位和最后一位数字之和(这里是完整的问题定义 https://www.codechef.com/problems/FLOW004/)。我通过了示例输入,但在提交时给了我错误的答案。我应该如何调试我的代码。请参考以下给出错误答案的代码,比如如何识别不同类型的输入,使用哪些输入可以尝试检测错误。

#include <stdio.h>
#include <math.h>

int main(void) {
    int t, n, last_term, first_term;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        last_term = n % 10;
        while(abs(n) > 10)
        {
            n = n / 10;
        }
        first_term = n;
        printf("%d\n", abs(first_term) + abs(last_term));
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

条件 abs(n) > 10 看起来不对。

应该是 abs(n) >= 10abs(n) > 9 循环直到数字变成一位数长。

相关问题