You have 2 primary problems in your code.
(1) Do not include '\n'
in your format specifier. Format specifiers such as "%f"
skip whitespace by default. So use (subject to #2):
scanf("%f", &base)
(2) Validate EVERY user input by checking the return of the input function used. What happens if the user reached for the '4'
key by hit 'R'
my mistake? What happens then? (if it is the 1st digit -- undefined behavior as you blindly assume the input succeeded). Instead, validate the return, e.g.
if (scanf("%f", &base) != 1) {
fputs ("error: invalid float - base.\n", stderr);
return 1;
}
Putting it altogether, you could do:
#include <stdio.h>
int main (void)
{
float base, height, area;
fputs ("area of triangle=?\nbase=", stdout);
if (scanf("%f", &base) != 1) {
fputs ("error: invalid float - base.\n", stderr);
return 1;
}
fputs ("height=", stdout);
if (scanf("%f", &height) != 1) {
fputs ("error: invalid float - height.\n", stderr);
return 1;
}
area = base * height / 2.;
printf ("\narea = %f\n", area);
return 0;
}
(note: nit - there is no need to use the variadic printf
function if there are no conversions involved, simply use fputs
(or just puts
if you want a default '\n'
at the end). A good compiler will optimize this for your, but showing an understanding of what the proper tool for the job is has merit)
Example Use/Output
$ ./bin/trianglearea
area of triangle=?
base=3
height=4
area = 6.000000
Look things over and let me know if you have further questions.