I worked on this yesterday about 5 hours and got the code to work using help from this site, but I think the way I did it was a cheater way, I used a scanf command. Anyways I want to fix this the correct way. Thanks guys! Oh the code compiles but the average that gets spit out is wrong. I would like to conceptually understand what I am doing wrong as well as finish the assignment.
#include <stdio.h>
#include <stdlib.h>
double get_number(int num);
main () {
double n1,n2,n3;
double average;
printf("\nCompute the average of 3 integers\n");
printf("--------------------------------\n");
n1 = get_number(1);
n2 = get_number(2);
n3 = get_number(3);
average = (n1 + n2 + n3)/3;
printf("The average is %0.2f\n",average);
}
double get_number(int num) {
double value = 0;
int c;
printf("Please input number %i: ", num);
while ((c = getchar()) != '\n') {
if ( (c<'0') || (c>'9') ) {
printf("Incorrect character entered as a number - %i\n",c);
exit(-1);
}
else {
c =value;
}
}
return(value);
}
Your
get_numberfunction always returns 0, because you never assign anything to thevaluevariable. I’m guessing you want:Instead of
To clarify:
You are reading a number digit by digit (with
getcharyou read a single character). So let’s say you read the digits1 2 3:When you read
1, you dovalue = value*10 + ('1' - '0')meaningvalue = 0 + 1 = 1.When you read
2, you do the same and getvalue = 1*10 + ('2' - '0')meaningvalue = 12.Same for
3.What you need to understand is that multiplying something by 10 adds a 0 at the end of that something. Adding a digit to something that ends with a zero replaces that 0 by that digit.
You must also understand that you are dealing with characters, which are actually integers. The character
'0'is represented by an ASCII code of let’s sayx.'1'is represented byx + 1etc. If you were to print the value of'0'+'3'it would not be3as you’d expect. This is why we subtract'0'(which isx) from the characters, to get the actual digits.Hope that clears some things up.