0

Every time i print height or length, the value is 0. It's like C doesn't save the value of xHeight, yHeight, xLength or yLength. I checked, and i don't think is a syntax problem.

#include <stdio.h>
#include <stdlib.h>

int main()
{

float xHeight,yHeight,xLength,yLength, height = 0.0, length = 0.0;

printf("Tell me the x and y: \n");
scanf(" %.2lf", &xHeight);
fflush(stdin);
scanf("%.2lf",&yHeight);
fflush(stdin);


height = xHeight - yHeight;;
printf("\n%.2lf",height);

printf("Now tell me another x and y: \n");
scanf(" %.2lf", &xLength);
fflush(stdin);
scanf("%.2lf",&yLength);
fflush(stdin);


length = xLength - yLength;
printf("\n%.2lf", length);

printf("\n==========================================\n");


printf("The perimeter of this rectangle is %.2lf", 2*(length+height));

return 0;
}
Steve Summit
  • 45,437
  • 7
  • 70
  • 103
Boropap
  • 25
  • 3
  • 4
    [Warnings](https://godbolt.org/z/K39sYjq49). They are [your friends](https://stackoverflow.com/questions/57842756/). – n. m. could be an AI Jun 17 '21 at 21:50
  • 5
    If your compiler isn't warning you about those scanf calls, turn up warning options till it does. `-Wall -Wextra` is a good start for GCC and clang. – Shawn Jun 17 '21 at 21:51
  • 4
    Also, always check the return value of scanf for errors before trying to use variables it sets. And `fflush(stdin);` is undefined. – Shawn Jun 17 '21 at 21:52
  • 2
    The format specifier you are using for `scanf` is `%.2lf`, but should be `%.2f` for an ordinary `float`. `lf` is for `double` – SGeorgiades Jun 17 '21 at 21:53
  • 1
    Ether change `lf` to `f` in your `scanf` calls, or else change your floating point type to `double` (which I would do anyway - there's rarely a need to use `float`). – Tom Karzes Jun 17 '21 at 21:57
  • @Shawn, ... and on platforms where `fflush(stdin)` *is* defined, it may delete important input. Never use it. – HAL9000 Jun 17 '21 at 22:19

1 Answers1

2

%.2lf is not a proper conversion specification for a float. There should be no .2, because scanf does not use a precision amount, and it should be f not lf, because f is for a pointer to a float while lf is for a pointer to a double.

You also do not need a space character before %f in scanf; the %f conversion automatically skips initial white space.

Use scanf("%f", &xHeight); and similarly in the other scanf calls.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312