我为一个家庭作业问题编写了这段代码,希望我通过使用指针算术(而不是订阅)来访问数组元素来编写内积。但是,程序不允许我在输入第三个元素后输入数字。为什么?

int inner_product(int *a, int *b, int size)
{
  int sum = 0, i;

  for (i=0; i<size; i++)
  {
    printf("enter value for first array: ");
    scanf("%d",*(a+i));
  }

  for (i=0; i<size; i++)
  {
    printf("enter value for second array: ");
    scanf("%d",*(b+i));
  }

  for (i=0; i<size; i++)
  sum += *(a+i) * *(b+i);

   return sum;
}


int main()
{
    int n, *a, *b;
    printf("How many elements do you want to store?  ");
    scanf("%d",&n);
    a=(int *)malloc(n*sizeof(int));
    b=(int *)malloc(n*sizeof(int));

    printf("%d\n",inner_product(a,b,n));

    free(a);
    free(b);
}

最佳答案

你可以修正警告。

$ gcc main.c
main.c: In function ‘inner_product’:
main.c:11:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
         scanf("%d",*(a+i));
               ^
main.c:17:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
         scanf("%d",*(b+i));

如果修复了警告,则可以输入4个元素:
$ ./a.out
How many elements do you want to store?  4
enter value for first array: 2
enter value for first array: 3
enter value for first array: 4
enter value for first array: 5
enter value for second array: 3
enter value for second array: 4
enter value for second array: 5
enter value for second array: 6
68

我刚把调用从int改为pointer。
#include <stdio.h>
#include <stdlib.h>

int inner_product(int *a, int *b, int size)
{
    int sum = 0, i;

    for (i=0; i<size; i++)
    {
        printf("enter value for first array: ");
        scanf("%d",(a+i));
    }

    for (i=0; i<size; i++)
    {
        printf("enter value for second array: ");
        scanf("%d",(b+i));
    }

    for (i=0; i<size; i++)
        sum += *(a+i) * *(b+i);

    return sum;
}


int main() {
    int n, *a, *b;
    printf("How many elements do you want to store?  ");
    scanf("%d", &n);
    a = (int *) malloc(n * sizeof(int));
    b = (int *) malloc(n * sizeof(int));

    printf("%d\n", inner_product(a, b, n));

    free(a);
    free(b);
}

关于c - C的内积,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37118993/

10-11 18:48