-1

when i input base value, it will not be recognized first in c

#include <stdio.h>

main(void)
{
    float base, height, area;

    printf("area of triangle=?\n");
    printf("base=");
    scanf("%f\n", &base);
    printf("height=");
    scanf("%f\n", &height);
    area = base*height / 2;

    printf("area = %f\n", area);

    return 0;
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
Ree Mae
  • 11
  • 2

3 Answers3

1

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.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

Scanf using only format

scanf("%f",&base);
Ponsakorn30214
  • 267
  • 4
  • 11
-1
printf("base=");
scanf("%f", &base);
printf("\n");
printf("height=");
scanf("%f", &height);
printf("\n");
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278