Soloway's recurring rainfall

From Rosetta Code
Revision as of 18:13, 10 September 2022 by AssKoala (talk | contribs)
Task
Soloway's recurring rainfall
You are encouraged to solve this task according to the task description, using any language you may know.

Soloway's Recurring Rainfall is commonly used to asses general programming knowledge by requiring basic program structure, input/output, and program exit procedure.

The problem:

Write a program that will read in integers and output their average. Stop reading when the value 99999 is input.

References:

C

#include <stdio.h>

int main(int argc, char **argv)
{
	// Unused variables
	(void)argc;
	(void)argv;
	
	float currentAverage = 0;
	unsigned int currentEntryNumber = 0;
	
	for (;;)
	{
		int ret, entry;
		
		printf("Enter rainfall int, 99999 to quit: ");
		ret = scanf("%d", &entry);
		
		if (ret)
		{
			if (entry == 99999)
			{
				printf("User requested quit.\n");
				break;
			}
			else
			{
				currentEntryNumber++;
				currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage;
				
				printf("New Average: %f\n", currentAverage);
			}
		}
		else
		{
			printf("Invalid input\n");
			while (getchar() != '\n');	// Clear input buffer before asking again
		}
	}
	
	return 0;
}