c - 函数无明显原因重复运行
问题描述
我正在编写一个应该将整数平均在一起的程序,并在输入时检查一个数字是否为负。一切似乎都正常,直到返回一个值,然后它似乎重复运行我的函数,我不知道为什么。我会用谷歌搜索我的问题,但我什至不知道要查找什么。
#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;
}
解决方案
您的函数重复运行,因为它是递归的(它调用自己)并且printf
每次调用函数时都会执行所有这些。如果您只想打印最终结果,请执行main
以下操作:
printf("%f\n", number);
我不确定您在这里要做什么,但是如果您想要在每次引入数字时打印部分平均值,那么您应该在递归调用函数之前进行打印。否则,当您完成输入数字时,您将获得所有打印。
我给你的最后一条建议是,你应该注意代码中的结构和组织。看起来很乱。
推荐阅读
- azure - 需要 powerhsell 命令来检查文件是否存在于文件存储中且没有错误
- image - brcc32 无效位图格式(降低图像质量)
- wordpress - 我们是否将存储数据推送到数据库或保存数据然后在@wordpress/data 中更新存储
- python - 如何在 Django 中获得另一个特定用户的批准来更新表单?
- android - 如何静音推送通知?
- google-api - 将 Google 登录与 Google Calendar API 分开
- apache-kafka - What are stream-processing and Kafka-streams in layman terms?
- sql - 带有查询的 GCP 存储过程
- ruby - Ruby 等价于 Python 的常规数字分隔
- python - Pygame - event.pos 在 def main() 中不起作用