gpt4 book ai didi

c - 为什么下面的代码不能正确输出所有测试用例?

转载 作者:行者123 更新时间:2023-11-30 21:20:47 25 4
gpt4 key购买 nike

/*
*
*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)中输出正确,但在下一个测试用例中产生错误的输出。代码中有什么问题?请帮忙!提前致谢!

最佳答案

每次输入新字符串时,都需要初始化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;
}

关于c - 为什么下面的代码不能正确输出所有测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34708092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com