无法清除测试用例:我应该为此编写代码:

时间:2017-07-09 15:33:28

标签: c testcase

Apple和Orange问​​题。

12个测试用例中只有3个被清除。从几个小时开始就想不出别的什么。

样本输入0

7 11
5 15
3 2
-2 2 1
5 -6

样本输出0

1
1

问题:https://www.hackerrank.com/challenges/apple-and-orange/problem

代码

int main(){

    int s; 
    int t; 
    scanf("%d %d",&s,&t);

    int a; 
    int b; 
    scanf("%d %d",&a,&b);

    int m; 
    int n; 
    scanf("%d %d",&m,&n);

    int *apple = malloc(sizeof(int) * m);
    for(int apple_i = 0; apple_i < m; apple_i++){
       scanf("%d",&apple[apple_i]);
    }


    int *orange = malloc(sizeof(int) * n);
    for(int orange_i = 0; orange_i < n; orange_i++){
       scanf("%d",&orange[orange_i]);
    }

    int fellap=0;
    int fellor=0;
    int d;

    for(int apple_i = 0; apple_i < m; apple_i++){
        d=apple[apple_i]+a;
        f(d>=s && d<=t){
            fellap++;
        }
    }

    for(int orange_i = 0; orange_i < n; orange_i ++){
        d=orange[orange_i]+b; 
        if(d>=s&&d<=t){
            fellor++;
        }
    }

    printf("%d\n", fellor);
    printf("%d\n", fellap);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您的代码中的错误非常简单。你已经切换了橘子和苹果的输出。变化

printf("%d\n", fellor);
printf("%d\n", fellap);

printf("%d\n", fellap);
printf("%d\n", fellor);

我认为不需要将所有值读入数组。您可以简单地遍历输入并同时进行计算。这是一个传递所有测试用例的示例:

传递所有测试用例的工作代码:

int main(){
    int s; 
    int t; 
    scanf("%d %d",&s,&t);
    int a; 
    int b; 
    scanf("%d %d",&a,&b);
    int m; 
    int n; 
    scanf("%d %d",&m,&n);

    int noApples=0;
    int noOranges=0;

    for(int apple_i = 0; apple_i < m; apple_i++){
        int apple;  
        scanf("%d",&apple);
        if (apple+a >= s && t >= apple+a) 
            noApples++;
    }

    for(int orange_i = 0; orange_i < n; orange_i++){
        int orange;
        scanf("%d",&orange);
        if (orange+b >= s && t >= orange+b)
            noOranges++;
    }
    printf("%d\n%d\n", noApples, noOranges);
    return 0;
}