首页 > 解决方案 > 函数无明显原因重复运行

问题描述

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

#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;
}

标签: c

解决方案


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

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

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


推荐阅读