繁体   English   中英

我如何制作这张照片?

[英]How Do I Make This Print?

我现在明白如何打印这些东西了:我忘了为数组分配 memory。 但是,现在我似乎无法在最终结果中正确计算数学。

迅速的:

一个男孩去商店买电子游戏。 该商店包含 N 个独特的视频游戏。 游戏的价格以数组 A 的形式给出。第 i 个游戏的价格为 A[i]。 现在男孩有 q 个查询,在每个查询中他想知道价格小于给定数量 M 的独特游戏的数量。输入:

第一行包含 integer N 商店中可用的独特视频游戏总数。

第二行包含 N 个空格分隔的整数(游戏价格)。

第三行包含 Q 个查询。

接下来的每一 Q 行包含 integer M. Output:

对于每个查询 output 该查询价格低于 M 的游戏数量。 样本输入:

 5 1 4 10 5 6 4 2 3 5 11

Output 用于样本输入:

 1 1 2 5

代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *Prices, UniqueGames, j, h, i, numPrice, numQueries, *PriceQueries, *TestResults;

    //Making Arrays
    printf("Enter number of unique games.");
    scanf("%d", &UniqueGames); // Array Size

    Prices = (int*)malloc(sizeof(int)*UniqueGames); // Memory Allocation

    for(j = 0; j < UniqueGames; j++){ // Filling Array
        scanf("%d", &h);
        *(Prices+j) = h;
    }

    printf("Enter number of queries.");
    scanf("%d", &numQueries); // Array Size

    PriceQueries = (int*)malloc(sizeof(int)*numQueries); // Memory Allocation

    for(j = 0; j < numQueries; j++){ // Filling Array
        scanf("%d", &h);
        *(PriceQueries+j) = h;
    }

    //Calculations
    TestResults = (int*)malloc(sizeof(int)*numQueries);
    h = 0;
    for(j = 0; j < numQueries; j++){ // Filling array TestResults with test results
        for (i = 0; i < UniqueGames; i++) {
            if (Prices[i] < PriceQueries[i]) {
                h = h + 1;
                TestResults[j] = h;
        }
            else {
                h = 0;
            }

        }
        printf("%d\n", TestResults[j]);

    }

    free(Prices);
    free(PriceQueries);
    free(TestResults);
   return 0;
}

我正在为每个游戏填写一组价格,并为用户输入的查询数量填写一组价格。 我根据查询集中的价格填充了一组测试结果,我正在尝试打印最终的数组。

您的“计算”不必要地复杂,难以理解。 (而且不稳定的缩进也无济于事。)

//Calculations
TestResults = (int*)malloc(sizeof(int)*numQueries); // <== uninitialised array
h = 0;
for(j = 0; j < numQueries; j++){ // Filling array TestResults with test results
    for (i = 0; i < UniqueGames; i++) {
        if (Prices[i] < PriceQueries[i]) { // <= one index should be 'j'
            h = h + 1;
            TestResults[j] = h; // <== assignment should be accumulation
    }
        else {
            h = 0; // <== why reset???
        }

    }
    printf("%d\n", TestResults[j]); // <== why use an array???

}

重写(带注释)可能有助于澄清您似乎想要实现的目标

//Calculations
for( j = 0; j < numQueries; j++ ) { // for each query amount...
    int cnt = 0; // count the games...
    for( i = 0; i < UniqueGames; i++ ) // for each game
        if( Prices[ i ] < PriceQueries[ j ] ) // priced less than this query amount
            cnt++;

    printf( "Query %d: %d games cost less than %d\n", j, cnt, PriceQueries[ j ] );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM