我该如何操作数组?

时间:2022-05-11 09:20:02

I have an array

我有一个阵列

arr[]={7,5,-8,3,4};

And I have to update the same array to

我必须更新相同的数组

arr[]={7,12,4,7,11};

my code:

#define _CRT_SECURE_NO_WARNINGS

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

int sumArr(int *arr, int size);

void main()
{

    int arr[] = { 7,5,-8,3,4 };
    int i, size, res = 0;

    printf("Enter Size Of The Array:");
    scanf("%d", &size);

    res = sumArr(arr, size);

    for (i = 0; i < size; i++)
    {
        printf("%d\n", res);
    }

  }


int sumArr(int *arr, int size)
{

        int i;

    for (i = 0; i < size; i++)
    {
      arr[i+1]+= arr[i];

        printf("  %d  \n", arr[i + 1]);
    }

    return arr[i+1];
}

The output should be: 7,12,4,7,11 But in my code, the output is: 12,4,7,11,-858993449,58196502,58196502,58196502,58196502,58196502

输出应为:7,12,4,7,11但在我的代码中,输出为:12,4,7,11,-858993449,58196502,58196502,58196502,58196502,58196502

Any hints? I can use auxiliary functions for input and output arrays, will it help?

任何提示?我可以为输入和输出数组使用辅助函数,它会有帮助吗?

1 个解决方案

#1


3  

You have several mistakes in your code:

您的代码中有几个错误:

  • You need to stop the summing loop once i+1 reaches the end of the array
  • 一旦i + 1到达数组的末尾,您需要停止求和循环

  • Your code knows the size; there is no need to read it from end-user
  • 你的代码知道大小;没有必要从最终用户那里阅读它

  • You need to print the value of res once, rather than printing it in a loop
  • 您需要打印res的值一次,而不是在循环中打印它

  • You should consider moving the printing portion of the program into main from sumArray.
  • 您应该考虑将程序的打印部分从sumArray移动到main。

The modifications are very straightforward:

修改非常简单:

int sumArr(int *arr, int size) {
    // Stop when i+1 reaches size; no printing
    for (int i = 0; i+1 < size; i++) {
        arr[i+1]+= arr[i];
    }
    return arr[size-1];
}

Printing in the main:

主要印刷:

printf("sum=%d\n", res);
for (int i = 0; i < size; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}

Demo.

#1


3  

You have several mistakes in your code:

您的代码中有几个错误:

  • You need to stop the summing loop once i+1 reaches the end of the array
  • 一旦i + 1到达数组的末尾,您需要停止求和循环

  • Your code knows the size; there is no need to read it from end-user
  • 你的代码知道大小;没有必要从最终用户那里阅读它

  • You need to print the value of res once, rather than printing it in a loop
  • 您需要打印res的值一次,而不是在循环中打印它

  • You should consider moving the printing portion of the program into main from sumArray.
  • 您应该考虑将程序的打印部分从sumArray移动到main。

The modifications are very straightforward:

修改非常简单:

int sumArr(int *arr, int size) {
    // Stop when i+1 reaches size; no printing
    for (int i = 0; i+1 < size; i++) {
        arr[i+1]+= arr[i];
    }
    return arr[size-1];
}

Printing in the main:

主要印刷:

printf("sum=%d\n", res);
for (int i = 0; i < size; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}

Demo.