【问题标题】:Why the code below does not outputs correctly for all test cases?为什么下面的代码不能正确输出所有测试用例?
【发布时间】:2016-01-10 16:48:33
【问题描述】:
/*
*
*Program for finding total number of holes in a string.
*For example total number of holes in "ANUBHAV" is 4 and in "GOURAV" is 3
*
*/
#include <stdio.h>
#include<string.h>
// start of main function
int main(void) {
    int t,i = 0,hole = 0; // variable declaration
`   char str[100];
    scanf("%d",&t); // input number of test cases
    while(t--)
    {
        scanf("%s",str);  // input string
        while(i < strlen(str))
        {
            if(str[i] == 'B')
            {
                hole += 2;
            }
            else if(str[i] == 'A' || str[i] == 'D' || str[i] == 'O' || str[i] == 'P' || str[i] == 'Q' || str[i] == 'R' )
            {
                hole += 1;
            }

            i = i + 1;  
        }
        printf("%d",hole); //printing the total number of holes
    }
    return 0;
}

此代码在第一个测试用例(t)中正确输出,但在下一个测试用例中产生错误输出。代码中有什么问题? 请帮忙! 提前致谢!

【问题讨论】:

  • 代码应该做什么?
  • 可能是因为您的 main 函数中有一个杂散的反引号...

标签: c string loops ide codeblocks


【解决方案1】:

每次输入新字符串时都需要初始化hole。你的代码也可以改进很多,检查一下

/*
*
*Program for finding total number of holes in a string.
*For example total number of holes in "ANUBHAV" is 4 and in "GOURAV" is 3
*
*/
#include <stdio.h>
#include <string.h>
// start of main function
int main(void)
{
    int hole; // variable declaration
    int count;
    char str[100];
    if (scanf("%d", &count) != 1)
        return -1; // Input Error
    for (int i = 0 ; i < count ; ++i)
    {
        hole = 0;
        if (scanf("%99s", str) != 1)
            return -1; // Input Error
        for (int j = 0 ; str[j] != '\0' ; ++j)
        {
            switch (str[j])
            {
                case 'B':
                    hole += 2;
                    break;
                case 'A':
                case 'D':
                case 'O':
                case 'P':
                case 'Q':
                case 'R':
                    hole += 1;
                    break;
            }
        }
        printf("Holes in %s -> %d\n", str, hole); //printing the total number of holes
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    解决方案:-

    在你的代码中,你应该在循环中初始化hole

    while (t--) {
    int hole = 0;
    .
    .
    }
    

    说明:-

    hole 的计数对于每个测试用例都是不同的。如果没有为每个测试用例在0 初始化,则显示的计数将与之前的计数相加,从而导致错误的结果。

    例如,如果 test_case_0 有 2 个孔,则将孔设置为 2,然后,如果 test_case_13 孔,并且孔不会重置为 @ 987654327@,最终结果将是test_case_1的孔设置为5,这是导致错误的原因。

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      您应该在 while 语句中和 printf 函数之后设置 hole=0 的值。因为下一个测试用例的孔值不会改变。

      【讨论】:

        猜你喜欢
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-20
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        相关资源
        最近更新 更多