Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 函数无明显原因重复运行_C - Fatal编程技术网

C 函数无明显原因重复运行

C 函数无明显原因重复运行,c,C,我正在编写一个程序,该程序应该将整数平均在一起,并在输入时检查数字是否为负数。一切似乎都在运行,直到返回一个值,然后它似乎会重复运行我的函数,我不知道为什么。我会用谷歌搜索我的问题,但我甚至不知道该查什么 #include <stdio.h> double averageOrNegative(int sum, int counter); int main(){ int sum = 0, counter = 0; double number = averageOrNe

我正在编写一个程序,该程序应该将整数平均在一起,并在输入时检查数字是否为负数。一切似乎都在运行,直到返回一个值,然后它似乎会重复运行我的函数,我不知道为什么。我会用谷歌搜索我的问题,但我甚至不知道该查什么

#include <stdio.h>
double averageOrNegative(int sum, int counter);
int main(){
    int  sum = 0, counter = 0;
    double number = averageOrNegative(sum,counter);
    return 0;
}
double averageOrNegative(int sum, int counter){//the sum and counter are declared outside the function so they don't get reset when I call it again
    int input = 0;
    double result = 0;
    char yesORno = ' ';
    printf("\nPlease input a number \n");
    scanf("%d", &input);
        if(input >= 0){
            counter++;
            sum = sum + input;
            printf("\ndo you want to input another number, press y for yes\n");
            scanf(" %c", &yesORno);
                if(yesORno == 'y'){
                    averageOrNegative(sum, counter);//this prompts for another number by calling the function again
                }else{
                    result = sum/counter;//this averages the numbers together and returns the result
                }
        }else{
            result = input;//if the number was negative, it becomes the return value
        }
    printf("\n%d", sum);
    printf("    %d", counter);
    printf("\nthis is being run\n");//these 4 lines are only here to test
    printf("\n%f", result);
    return result;
}
#包括
双平均或负(整数和,整数计数器);
int main(){
整数和=0,计数器=0;
双倍数=平均或负(和、计数器);
返回0;
}
double averageOrNegative(int-sum,int-counter){//sum和counter在函数外部声明,因此当我再次调用它时,它们不会被重置
int输入=0;
双结果=0;
char yesORno='';
printf(“\n请输入一个数字\n”);
scanf(“%d”,输入(&I));
如果(输入>=0){
计数器++;
总和=总和+输入;
printf(“\n要输入另一个数字,请按y键表示是”\n”);
scanf(“%c”和“yesORno”);
如果(yesORno=='y'){
averageOrNegative(sum,counter);//通过再次调用该函数,提示输入另一个数字
}否则{
result=sum/counter;//将这些数字相加求平均值并返回结果
}
}否则{
结果=输入;//如果数字为负数,则它将成为返回值
}
printf(“\n%d”,总和);
printf(“%d”,计数器);
printf(“\n正在运行”;//这4行仅用于测试
printf(“\n%f”,结果);
返回结果;
}

您的函数重复运行,因为它是递归的(它自己调用),并且每次调用函数时都会执行所有这些
printf
。 如果只想打印最终结果,请在
main
中执行以下操作:
printf(“%f\n”,数字)

我不知道你想在这里做什么,但是如果你想在每次引入一个数字时打印部分平均值,那么你应该在递归调用函数之前打印。否则,当您完成输入数字时,您将获得所有打印


我最后给您的建议是,您应该注意代码中的结构和组织。看起来很混乱。

请使用标题与代码沟通问题。