【问题标题】:How to split/divide array using user input如何使用用户输入拆分/划分数组
【发布时间】:2017-05-22 14:29:02
【问题描述】:
#include <stdio.h>

int main( )
{
    int length = 0;
    int divide = 0;
    int count = 0;
    int i;

    printf("Set the length of array: \n");
    scanf("%d", &length);
    int array[length];

    for(i = 0; i < length; i++)
    {
        scanf("%d", &array[i]);
    }
    printf("Divide array into subarray: \n");
    scanf("%d", &divide);
    for(i = 0; i < divide; i++)
    {
        int countfrom = length / divide * i;
        int countto = countfrom + length / divide;

        for(int j = countfrom; j < countto; j++)
        {
            if( array[j] == 1 && array[j+1] == 0 && array[j+2] == 1)
            {
                count++;
            }
        }
    }
    printf("count: %d\n", count);
    return 0; 
}

这是我目前所拥有的。目的是根据用户输入定义数组的长度并将其划分为子数组(int 除法也是来自用户输入)。 主要目的是统计序列的次数,在划分的子数组中找到101。它工作得很好,除了奇怪的值。例如,array[length(value: 17)] = {1, 0, 1, 2, 7, 9, 6, 5, 0, 1, 0, 1, 0, 1, 1, 0},如果除法值为 5,那么子数组应该是, {1, 0, 1}, {2, 7, 9}, {6, 5, 0}, {0, 1, 0}, {1, 0, 1}, {1, 0},计数的值应该是 3。但是,它会打印出 4。

【问题讨论】:

  • 你应该和你的同学一起工作stackoverflow.com/questions/44113321/… 注意我们不是编码/辅导服务。您对您的代码有具体的问题吗?
  • 我认为该代码中的问题在于条件数组 [j]... 有什么办法解决它吗?
  • {1, 0, 1, 2, 7, 9, 6, 5, 0, 1, 0, 1, 0, 1, 1, 0} and if the divide value is 5, then the subarrays should be, {1, 0, 1}, {2, 7, 9}, {6, 5, 0}, {0, 1, 0}, {1, 0, 1}, {1, 0} 是错字。第一次修复它。此外,您的代码正在越界访问。
  • 那么为什么你有两个身份,并且重复发布同一个问题?这违反了网站规则!
  • @JohnBollinger 我猜样本输入应该是1,0,1,2,7,9,6,5,0,1,0,1,1,0,1,1,0

标签: c arrays computer-science


【解决方案1】:

我最初将“在划分的子数组中找到 101”误解为意味着子数组实际上必须是 101。如果要搜索子数组,确实需要 j 循环,但确实需要边界检查。

         if( array[j] == 1 && array[j+1] == 0 && array[j+2] == 1)

应该是

        if( j+2 < countto && array[j] == 1 && array[j+1] == 0 && array[j+2] == 1)

(或者您可以最初将 countto 减 2,然后将其调整为最多 length-2)。

原答案:

根据您的描述,您似乎根本不需要 j 循环或 countto;在 i 循环中,您应该只检查 array[countfrom]==1 &amp;&amp; array[countfrom+1]==0 &amp;&amp; array[countfrom+2]==1 (并且首先检查 countfrom + 2

但是您的代码假设您有长度为 3 的“子数组”;您应该检查给定输入是否确实如此,如果不是,则给出错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多