c语言中不同大小的减法数组 void函数(int first[],int second[],int third[]{ int i; 对于(i=0;i

c语言中不同大小的减法数组 void函数(int first[],int second[],int third[]{ int i; 对于(i=0;i,c,arrays,C,Arrays,一个选项是添加额外的循环变量: void function(int first[], int second[], int third[]) { int i; for(i=0;i<64;i++) { third[i] = first[i] - second[i]; } } 使用print\u array作为一个功能,以避免每次打印时重复相同的代码行 对于示例输入,输出将为0 0 2 4 第一个和第二个数组的元素是正数序列

一个选项是添加额外的循环变量:

void function(int first[], int second[], int third[]) {
       int i;
       for(i=0;i<64;i++) {
          third[i] = first[i] - second[i];
       }
    }
使用
print\u array
作为一个功能,以避免每次打印时重复相同的代码行

对于示例输入,输出将为
0 0 2 4

第一个和第二个数组的元素是正数序列 数字,它们都以-1结尾

你可以做如下的事情

维护两个索引
i
j
。 其中,
i
将索引较大数组,
j
将索引较小数组,一旦较小数组达到-1,将
j
重置为0,一旦较大数组达到-1,则中断循环

#include <stdio.h>

void print_array(int arr[], int);
void function(int arr_1[], int arr_2[], int arr_3[], int, int);

int main()
{
    int arr_1[] = {1,2,3,4,5};
    int arr_2[] = {1,2};

    int n_1 = sizeof(arr_1)/sizeof(arr_1[0]);
    int n_2 = sizeof(arr_2)/sizeof(arr_2[0]);  

    int arr_out[n_1]; 

    function(arr_1, arr_2, arr_out, n_1, n_2);

    print_array(arr_1, n_1);
    print_array(arr_2, n_2);
    print_array(arr_out, n_1);

    return 0;
}

void print_array(int arr[], int n_elem)
{
    int i = 0;
    for (i=0; i<n_elem; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
void函数(int first[],int second[],int third[]{
int i=0,j=0;

对于(i=0;i您可以使用
%
从数组的长度中获取索引的剩余部分,这样,您可以循环遍历第二个数组! 我更改了你的代码,按照你的要求执行

void function(int first[], int second[], int third[]) {
   int i =0,j=0;

   for(i=0; i<64 ; i++;j++) {

       if(second[j] == -1)
       {
          j =0; //Reset the j=0 to start from beginning 
       }

       if (first[i] == -1)
       {
          third[i] = -1; //Terminate third with -1
          break; //Break the loop
       }

      third[i] = first[i] - second[j];
   }
}
//在将数组传递给函数之前获取数组的长度,如下所示:
//int second_len=sizeof(second)/sizeof(second[0]);
空函数(int first[],int second[],int third[],int second_len){
int i;

对于(i=0;请参阅
%
运算符以获得一个简单的解决方案。我不确定,但我认为我应该提到一件重要的事情。第一个数组和第二个数组的元素是正数序列,它们都以-1结尾。@scylla0120,是否也要包括所有这些数字,-1?此代码适用于任何ar我试着用类似的方法来做,但我得到了以下结果:@scylla0120什么结果?523-120=513,523-120=12090971155,694-440=-75等等。@scylla0120我对我的答案做了一点修正。请现在试试。谢谢,现在它工作得很好:)
void function(int first[], int second[], int third[]) {
   int i =0,j=0;

   for(i=0; i<64 ; i++;j++) {

       if(second[j] == -1)
       {
          j =0; //Reset the j=0 to start from beginning 
       }

       if (first[i] == -1)
       {
          third[i] = -1; //Terminate third with -1
          break; //Break the loop
       }

      third[i] = first[i] - second[j];
   }
}
// get the length of array before you pass it to the function like this:
// int second_len = sizeof(second) / sizeof(second[0]);
void function(int first[], int second[], int third[], int second_len) {
    int i;
    for(i=0;i<64;i++) {
        third[i] = first[i] - second[i % second_len];
    }
}