My assignment is to fix the code. I have my edited code below and the original code below that. I figure I still have a few errors in here. My error checking doesnt seem to w
The issues with the original program are:
((c<'0') || (c>'9'))
. exit
function you need to include "stdlib.h".main
function to understand what is get_number
, you need to either move the function to be before the main
function, or you can use a forward declaration.=
) has lower precedence than the inequality operator (!=
), so you need to use parenthesis, like: ((c = getchar()) != '\n')
You have actually created several more issues, so I wouldn't rely on your code.
In any case, in general - it is advised you study how to use a debugger. Once your code is compiling (and for that you'll need to get accustomed to the compilation error messages), you need to start debugging your code. I suggest you take some time to learn how to set breakpoints, set watches, and go step by step into your code. That skill is absolutely essential for a good developer.
A few issues:
1. You should be using '9' and '0', since you want the ASCII values for digit '9' (0x39) and '0' (0x30), not 0x9 and 0x0.
if ( (c>'9') || (c<'0') ) {
2. != has higher precedence than =, so you need parens. Learn operator precedence, and if you're in doubt, use parens:
3. getchar
is a function not a variable.
while ((c = getchar()) != '\n') {
4. You use the wrong conversion. num
is a double, so you would need %f
. Or, you could make num
a int
.
printf("Please input number %f: ", num);
5. You never actually use c in any way (except error checking). You always return 0 or num
(see your else clause), which makes no sense. The else body of the original is correct.
You got the floating point parsing all wrong and shouldn't be doing it yourself. There's an easier way:
double get_number(double num) {
double value = 0.0;
printf("Please input number %lf: ", num);
scanf("%lf", &value);
return(value);
}
Here's how I'd go about correcting the code ...
For 1. I used the "original code" as posted by you.
For 2. I used int main(void)
, declared the function get_number
before defining main
, added parenthesis in line 20, and added #include <stdlib.h>
For 3. I added return 0;
before the final }
of main
. I also removed the extra output that messed up the ideone interface (it looks better on an interactive interface)
Edit more tests needed to complete the task of correcting the original code