简体   繁体   English

在循环中调用函数

[英]Calling a function within a loop

I am trying to a simple addition function that will take a number x from an array an and add a variable i to it, which is the iteration variable inside the for loop. 我正在尝试一个简单的加法函数,该函数将从数组an中获取数字x并向其中添加变量i ,这是for循环内的迭代变量。 Instead of adding each variable individually and producing the output of : 而不是单独添加每个变量并产生以下输出:

3, 2, 7 3 2 3

it produces values of 它产生的价值

3, 5, 13. 3 5 5

#include <stdio.h>
int add(int x[], int y);
int main(void) {
    int i;
    int a[3] = {3, 1, 5};
    for(i=0; i<3; i++)
    {
        printf("%d \t", i);
        printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
    }
    return 0;
}
int add(int x[], int y){
    return x+y;
}

Try 尝试

int add(int x, int y){
    return x+y;
}

In your function definition, 在您的函数定义中

int add(int x[], int y){

int x[] expects an array to be passed as the argument. int x[]期望将数组作为参数传递。 By calling that with 通过与

      add(a[i], i)

you're making multiple mistakes, like 您犯了多个错误,例如

  • passing an int value where int * is expected, so a wrong and implicit conversion from int to int * is talking place. 在期望使用int *地方传递int值,因此从intint *的错误和隐式转换正在讨论中。
  • Inside add() , x is of type int * . add()内部, x的类型为int * So, by saying return x+y; 因此,通过说return x+y; , you're essentially again (wrongly) converting a pointer to int type. ,本质上又是在(错误地)将指针转换为int类型。

Here, it seems, you need only one int variable. 似乎在这里,您只需要一个int变量。 not an array. 不是数组。 Change it (both declaration and definition) to 将其(声明和定义)更改为

int add(int x, int y){

Suggestion: Turn up the compiler warnings and pay heed to them. 建议:调出编译器警告并留意它们。 For example, with the -Wall option enabled, you would have received a warning saying 例如,启用-Wall选项,您将收到一条警告,说

warning: passing argument 1 of 'add' makes pointer from integer without a cast 警告:传递'add'的参数1会使指针从整数开始而无需强制转换

 printf("%d, %d, equals %d \\n", a[i], i, add(a[i], i)); ^ 

and

expected int * but argument is of type int 预期为int *但参数为int类型

 int add(int x[], int y); 

and, 和,

warning: return makes integer from pointer without a cast 警告:return从指针转换为整数而不进行强制转换

  return x+y; ^ 

You are using array as an argument. 您正在使用数组作为参数。 Please try below code: 请尝试以下代码:

#include <stdio.h>
int add(int x, int y);
int main(void) {
    int i;
    int a[3] = {3, 1, 5};
    for(i=0; i<3; i++)
    {
        printf("%d \t", i);
        printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
    }
    return 0;
}
int add(int x, int y){
    return x+y;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM