gpt4 book ai didi

c - 如何使用用户输入拆分/划分数组

转载 作者:行者123 更新时间:2023-11-30 19:51:25 24 4
gpt4 key购买 nike

#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 div 也来自用户输入)。主要目的是统计序列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。

最佳答案

我最初误解了“在划分的子数组中找到 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 && array[countfrom+1]==0 && array[countfrom+2]==1 (并且首先检查countfrom + 2 < length,这样就不会超出数组的末尾)。

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

关于c - 如何使用用户输入拆分/划分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115518/

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