Requirements for this task are as follows:
Read floating point values from stdin, each separated by a newline, and terminated by EOF.
The input values are in the range [-100,000 to +100,000].
The input will contain at least one floating-point value.
The input may contain blank lines: these should be ignored.
Apart from possible blank lines, the input is otherwise well-formed.
At EOF, output:
the smallest value seen
the largest value seen
the arithmetic mean of all the values seen
all accurate to two decimal places.
The output values must be separated by a single space character and followed by a newline character.
Examples:
Input:
7
5.6
6
Output:
5.60 7.00 6.20
Input:
11
Output:
11.00 11.00 11.00
In my code when I input 7, 5.6, and 6, my output is 5.60 7.00 5.77.
I know where the issue is but not sure how to fix it. My total variable says its value at EOF is 17.322826 which is definitely not correct.
#include <stdio.h>
int main() {
int i = 0;
float big = 0;
float small = 1000000;
float total;
float div = 0;
while (i == 0) {
float a = 0;
float flag = scanf("%f", &a);
if (flag == EOF) {
printf("%.2f %.2f %.2f %f %f\n", small, big, total / div, total, div);
break;
}
if (a > big) {
big = a;
}
if (a < small) {
small = a;
}
div++;
total = total + a;
}
return 0;
}
You forgot to initialize total to 0.
Further notes:
the classic C idiom for an infinite loop is for (;;) { ... }.
flag should be defined as an int
you should stop the loop when flag != 1 instead of just flag == EOF. An invalid input will cause the program to loop endlessly. You can actually drop this variable completely.
initializing big to 0 and small to 1000000 is incorrect: what if all values are negative? what if they are all very large?
Here is a corrected version:
#include <stdio.h>
int main(void) {
float a, big, small, total;
int div;
if (scanf("%f", &a) != 1)
return 1;
big = small = total = a;
div = 1;
while (scanf("%f", &a) == 1) {
if (big < a) {
big = a;
}
if (small > a) {
small = a;
}
div++;
total += a;
}
printf("%.2f %.2f %.2f\n", small, big, total / div);
return 0;
}
Related
Want to elicit average of entered real value,until negative value is entered.
My problem is
My calculation don't quit when negative value is entered
It keep asks printf sentence for 3 time.
What did I do wrong?
#include <stdio.h>
int main(void)
{
double total = 0.0;
double input=0.0;
int num = 0;
for (; input >= 0.0;)
{
total += input;
printf("real number(minus to quit):");
scanf_s("%1f", &input);
num++;
}
printf("average:%f \n", total / (num - 1));
return 0;
}
you have many problems with your code :
it's not %1f in the line scanf_s("%1f", &total); as %1f will give you undefined behavior , it's %lfas you are scanning a double , there is a big difference between number one and lower case L
the function called scanf returns an integer indicating how many elements could be assigned to the input that the user entered , so , you should do if(scanf_s("%lf", &input) == 1) to check if the assignment done successfully, that will help you in detecting if - is entered instead of the number
if the user entered a lonely - then sacnf will fail to convert and you have to take another approach
when you are printing the average in this line : printf("average:%f \n", total / (num - 1)); , you actually prints a double , so it's %lf instead of %f
the condition of the for loop is incorrect , you are saying for (; input >= 0.0;) but this will prevent you from entering any negative values as when entering a negative value , the for loop will break , so you could use while(1) instead of the for loop and only break when a - is entered alone
so here is my edited version of yours , I introduced a dummy string to read the buffer and check whether the input was a lonely - or not , and if not then I try to convert it to double and here is my edited solution :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char dummy[30];
double total = 0.0;
int num = 0;
double DecimalConverted = 0;
while(1)
{
printf("real number(minus to quit):");
fgets(dummy, 30, stdin); // gets the input into the buffer
if(dummy[0] == '-' && dummy[1] == '\n') // break from the loop on condition that '-' only entered
break;
// convert the string to decimal
DecimalConverted = strtod(dummy ,NULL);
if(DecimalConverted == 0)
printf("not a number\n");
else{
total += DecimalConverted;
num++;
}
}
printf("average:%lf \n", total / (num - 1));
return 0;
}
and here is the output :
real number(minus to quit):12
real number(minus to quit):-51
real number(minus to quit):-
average:-39.000000
I am creating a program that uses a while loop to provide multiple pieces of information from input given by the user. One of these pieces is the smallest number entered. I can't get it to print anything but 0. Any idea why?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float num, sum = 0, sm, lg = 0, count = 0, avg = 0;
printf("Please enter a series of numbers (-1 to terminate): ");
scanf("%f", &num);
while(num > -1){
sum += num;
if(lg < num)
lg = num;
if(sm > num)
sm = num;
scanf("%f", &num);
count++;
avg = sum / count;
}
printf("The sum of your numbers is: %.4f\n", sum);
printf("You entered %.4f numbers\n", count);
printf("The average of the numbers you entered is: %.4f\n", avg);
printf("The smallest number you entered is: %.4f\n", sm);
printf("The Largest number you entered is: %.4f", lg);
return 0;
}
ex entry- 15
43
22.5
57.6
-1
Output-
sum:138.1000
4 numbers entered
average: 34.5250
smallest: 0.0000
Largest: 57.6000
In your code, sm has an undefined value because you aren't initializing it. You can initialize it to something like a very large number (or, even better, INFINITY) so it can be properly compared. The same goes for lg: if you want it to work for negative values too, you should initialize it with a very small value (-INFINITY). You can use INFINITY by including math.h.
the posted code does not compile!
first, because it is missing the needed #include statements for the needed header files. Specifically:
#include <stdio.h>
Then regarding this code block:
if(sm > num)
sm = num;
on the first pass through the while() loop, the variable sm is not initialized so accessing its' contents is undefined behavior.
Also, if using visual studio in debug mode, then all the stack is cleared to 0, so no other value will ever be assigned to it. This is why the algorithm always returns 0
Here's what I regard as a workable program. It uses double rather than float; if you insist, you can change the types and (input) formats to suit your desires. It has no particular limit on the number of rows it will accept. It doesn't output anything if there were no inputs. There is absolutely no need to use an array for the calculations. It uses use +∞ and -∞ to initialize the smallest (min) and largest (max) values respectively. Even if the only input is +∞ or -∞ (spelled +Inf or -Inf, or +Infinity or -Infinity, optionally without the + sign, and with upper-case, lower-case or mixed-case spelling) the correct values are produced.
#include <stdio.h>
#include <math.h>
int main(void)
{
double min = +INFINITY;
double max = -INFINITY;
double sum = 0.0;
size_t cnt = 0;
double value;
while (scanf("%lf", &value) == 1)
{
sum += value;
cnt++;
if (value > max)
max = value;
if (value < min)
min = value;
}
if (cnt > 0)
{
printf("Count = %zu\n", cnt);
printf("Sum = %g\n", sum);
printf("Min = %g\n", min);
printf("Max = %g\n", max);
printf("Average = %g\n", sum / cnt);
}
return 0;
}
Given ten random values between -1E6 and +1E6:
989375.672
-826955.668
224850.463
-401605.702
-45457.787
259618.099
821069.496
-268408.724
-512449.113
-46404.246
the program produces the output:
Count = 10
Sum = 193632
Min = -826956
Max = 989376
Average = 19363.2
I should probably put a bit more control on the output formatting, but the %g option is quite useful for numbers with wide ranges. Given the input data, using %11.3f would work well (it was used to format the output from the random number generator I used).
Sorry for being such a novice.
For this question I used C language, and the libraries stdlio.h and stdlib.h.
Question
So a question is asking me to:
Open a text file named 'numbers.txt' in read mode. This text file
has 6 integers in it.
Read the 6 integers from that text file using a loop.
Calculate and display the total and average of those 6 integers.
The text file 'numbers.txt' holds the integers: 5, 10, 15, 20, 25.
Here's my code:
FILE *n;
n = fopen("numbers.txt", "r");
int a, num, sum = 0;
float avg;
for (a = 0; a < 6; a++) {
fscanf(n, "%d", &num);
sum = sum + num;
}
avg = sum / (a - 1);
printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
fclose(n);
Another variation of the question is that I need to use a while loop to read the integers in the text file.
Here's my code for that:
FILE *n;
n = fopen("numbers.txt", "r");
int a = 0, num, sum = 0;
float avg;
while (fscanf(n, "%d", &num) != EOF) {
fscanf(n, "%d", &num);
sum = sum + num;
a++;
}
avg = sum / a;
printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
fclose(n);
Problem
When I run each of the above programs, I expect this output:
Sum = 75
Average = 15.00
However I get this instead (for the first code):
Sum = 100
Average 20.00
And this (for the second code):
Sum = 55
Average = 18.00
How am I able to get the correct output from both of these programs?
Again I apologise for how basic this question is. Nonetheless, any help would be appreciated.
In the first one, you tried to read one-to many numbers, but since there were only 5 numbers, the last number was added twice to your sum, so you ended up adding an extra 25 to the sum to get 100.
In the second code, after reading the last number, the end of the file was reached, so your code did not get the opportunity to add the last read number, so you missed adding 25 to your sum.
You were much closer with your first code, just change the for-loop to only iterate 5 times
Here is my observation,
Case 2 : The problem is here in below two line of code
while (fscanf(n, "%d", &num) != EOF) { /* this is fine, scanf() stored read int into num */
fscanf(n, "%d", &num); /* this is not needed as overwrites previous num, just remove it */
/* some code */
}
Also this
avg = sum / a;
doesn't get you expected result as sum/a results in integer but you are assigning it to avg which is float. One way to overcome this is to do typecasting like below
avg = (float)(sum / a);
Sample code :
int main(void) {
FILE *n;
n = fopen("numbers.txt", "r"); /* always do error handling to make more robust code */
if(n == 0) {
#TODO error handling */
}
int a = 0, num, sum = 0;
float avg;
while (fscanf(n,"%d", &num) != EOF) {
//fscanf(n, "%d", &num);// remove this
sum = sum + num;
a++;
}
avg = (float)(sum / a);// typecast it
printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
fclose(n);
return 0;
}
Case 1 : Here
for (a = 0; a < 6; a++)
rotating loop fixed number of times may not be a problem for now but it creates issue when you don't know in advance how many integer number file having. so better rotate loop until EOF. For e.g
for (a = 0; ; a++) {
if(fscanf(n, "%d", &num) == 1) /* compare with return value */
sum = sum + num;
else
break;
}
Hello Stack Community!
I am having trouble calculating the correct average for 10 integers.
The expected output average is supposed to be 140.0 with one integer value recognized as not a positive program by the compiler.
This is what I have compiled, and it recognized the negative integer but the average still comes to 150.0
Just trying to figure out what I am missing here.
Thanks!
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
double avg;
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 10)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
}
}
// Calculate avg. Need to type cast since two integers will yield an integer
avg = (double) sum/count;
printf("average is %lf\n " , avg );
return 0;
}
Values are: 100 100 100 100 -100 100 200 200 200 200
You want to read exactly 10 positive numbers, with count from 0 to 9.
After reading 100 100 100 100 -100 100 200 200 200 200 the value of count is 9 (because -100 neither added to the sum nor counted), which is less that 10 so the loop is executed one more time.
This time scanf() fails, so value remains unchanged; effectively you are reading another 200.
This is why the sum of the numbers is 1500 and the average 150.
AlexP found the explanation: you must check the return value of scanf(), otherwise, you will silently accept input that is not a number and reuse the last converted value.
Also note that the cast in avg = (double) sum/count; applies to sum and binds stronger than /. It is considered good style to make this more explicit by writing avg = (double)sum / count;
Here is a modified version of your program:
#include <stdio.h>
int main(void) {
/* variable definitions */
int count, value, sum;
double avg;
/* Initializations */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 10) {
printf("Enter a positive Integer\n");
if (scanf("%d", &value) != 1) {
break;
}
if (value >= 0) {
sum = sum + value;
count = count + 1;
} else {
printf("Value must be positive\n");
}
}
// Calculate avg.
// Need to type cast to force floating point division instead of integer division
if (count > 0) {
avg = (double)sum / count;
printf("average is %f\n", avg);
}
return 0;
}
If I understand your problem correctly, this is what you want to do :
int last_known_positive_value = 0;
// Loop through to input values
while (count < 10)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
last_known_positive_value = value;
}
else {
printf("Value must be positive\n");
sum = sum + last_known_positive_value;
}
count = count + 1;
}
check-answer-here
There are a number of different ways to approach the problem. (1) you can read your values as a string with fgets and then call sscanf and gain the benefit of a NULL return from fgets indicating EOF and a test of the buffer containing only '\n' to indicate a user pressed [Enter] to signal end of input.
(2) you can read the values numerically with scanf and then check for EOF to indicate end of input, or some other predetermined sentinel.
Regardless of which you choose, the approach is basically the same. (a) make a call to the function you are using for input, (b) check the RETURN, and (c) validate the value input is within the required range, and handle the data.
You get the drift, on all input, check the return of your read function and handle any error or EOF condition, then validate the input is within the expected range.
A quick example using your code and reading numeric values with scanf could be something like:
#include <stdio.h>
int main (void) {
/* define/initialize variables */
int count = 0, value = 0, sum = 0;
double avg = 0.0;
while (1) { /* infinite loop to process input */
int rtn;
printf ("Enter a positive Integer ([ctrl+d] to quit): ");
if ((rtn = scanf ("%d", &value)) != 1) {
if (rtn == EOF) { /* always handle user cancellation of input */
putchar ('\n'); /* tidy up with POSIX line ending */
break; /* on to final calculation */
}
}
if (value < 0) /* check out of range */{
printf ("Value must be positive\n");
continue; /* try again */
}
sum = sum + value; /* compute sum */
count = count + 1; /* increment count */
}
/* Calculate avg. (typecast to avoid integer division) */
avg = count > 0 ? (double) sum/count : 0; /* protect div by zero */
printf ("\n (%d/%d) => average: %lf\n", sum, count, avg);
return 0;
}
Example Use/Output
$ ./bin/sumavg < <(echo "100 100 100 100 -100 100 200 200 200 200")
Enter a positive Integer ([ctrl+d] to quit):
<snip>
(1300/9) => average: 144.444444
One common thread running between all complete examples is to always handle a manual EOF generated by the user allowing them to cancel an individual input, or input as a whole (you decide based on your needs). On Linux the manual EOF is generated by [ctrl+d] on windoze [ctrl+z].
Look all answers over and let me know if you have any questions related to the above.
while (count < 10) {
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum += value;
count++;
}
else {
printf("Value must be positive\n");
count++;
}
}
This will increment "count" even if negative integer is inputted.
Thus you will get the desired average.
The Code is supposed to make change for a dollar and works fine. but the professor says that he will be enter random numbers along with letters. It works fine with numbers but when a letter is entered an infinite loop will occur any suggestions?
#include <stdio.h>
#include <stdlib.h>
#define amtPaid 1
#define SENTINAL -1
int quarters(int numChange);
int dimes(int numChange);
int nickels(int numChange);
int pennies(int numChange);
int main(void)
{
double amtDue = 0; // how much is paid
while(1){
printf("\nPlease enter the price less than 1 dollar: ");
scanf(" %lg", &amtDue);
int changeReturn = (amtPaid - amtDue) * 100 + 0.5; // convert decimal to whole number
int updated = 0; // remaining change after amt of change
int numberQuarters = quarters(changeReturn); // number of quarters needed
if(changeReturn >= 0 && changeReturn <= 100){ // if changereturn is between 0 and 100 execute code
printf("\nNice!");
printf("\nWe owe you %i cents" , changeReturn);
if(numberQuarters >= 0){ // get and print number of quarters
printf("\nQuarters: %i", numberQuarters);
updated = changeReturn % 25;
}
if(dimes(updated) >= 0){ // get and print number of dimes
printf("\nDimes: %i", dimes(updated));
updated = updated % 10;
}
if(nickels(updated)>= 0){ // get and print number of nickels
printf("\nNickels: %i", nickels(updated));
updated = updated % 5;
}
if(pennies(updated) >= 0){ // get and print number pennies
printf("\nPennies: %i", pennies(updated));
}
}
else if(amtDue == SENTINAL){
break;
}
else {
printf("That does not make sense to me. please type a valid number");
}
printf("\n %g", amtDue);
}
return 0;
}
int quarters(int numChange){
int numQuarters = 0;
numQuarters = numChange / 25;
return numQuarters;
}
int dimes(int numChange){
int numDimes = 0;
numDimes = numChange / 10;
return numDimes;
}
int nickels(numChange){
int numNickels = 0;
numNickels = numChange / 5;
return numNickels;
}
int pennies(numChange){
return numChange;
}
In case an inappropriate value is supplied other than the expected value of the format specifier with scanf(), the scanf() will fail and the inappropriate value will remain in the input buffer, providing the feed to next scanf(), only to cause successive failures. In that case, you need to clean up the input buffer before going for next input. You can use something like
check the return value of scanf()
In case of failure, use while( getchar() != '\n' ); to clean the input buffer.
That said, int nickels(numChange) is now invalid in c (C99 onwards). You have to make it as int explicitly.
Instead of using scanf(" %lg", &amtDue);, get the user input as a string, so you can do proper checking.
char input[500];
fgets(input, 500, stdin);
// do some input checking
double val = atof(input);
// do calculations on the number
To check, there's all kinds of functions to help you in ctype.h, one that you might find interesting is isalpha.
Manual References:
fgets
atof converts string to double
atoi converts string to integer
isalpha