Soloway's recurring rainfall: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created page with "{{task}} 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:''' * http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf * https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppl...")
 
No edit summary
Line 9: Line 9:
* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf
* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf
* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf
* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf

=={{header|C}}==
<syntaxhighlight lang="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;
}
</syntaxhighlight>

Revision as of 18:13, 10 September 2022

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