Why is my program for printing in the program 0.000000 here?

I just started learning C programming. My book has this piece of code:

/*Code Start*/ /*This code is use to find the simple interest*/ main () { int p, n; float r, si; p = 1000; n = 3; r = 8.5; si= p*n*r/100; printf("%f", si); } /*Code end*/ 

The output I received was "255.000000"

I, although I will modify it using the scanf function, so I wrote the following:

 /*Code Start*/ main () { int p, n; float r, si; printf("Enter value for p: \n"); scanf("%d", &p); printf("Enter value for n: \n\n"); scanf("%d", &n); printf("Enter valuse for r: \n\n"); scanf("%d", &r); si= p*n*r/100; printf("\nYour Simple Interest is %f\n\n", si); } /*Code End*/ 

No matter what values ​​I give p, n, r, I always get 0.000000 ..
I also tried to give values, p = 1000, n = 3, r = 8.5, but still I get 0.000000 ..

+4
source share
6 answers

Firstly, your main problem: the %d specifier is for integers only, not float or double s. Use %f for float s.

In addition, main should return int , this will do:

 int main() { /* your code */ return 0; } 

Finally, I would recommend that you better use white space, as it will make reading much easier as soon as you start creating larger programs.

+4
source

Change the qualifier in scanf . You use %d instead of %f :

 scanf("%f", &r); ^ 
  • First note: the code looks bad (no return type for main ?!). Are you sure this is a good book?
  • Second note: using float today is pointless. Maybe you should use double ?
+6
source

Use the %f conversion specification to read float :

 scanf("%f", &r); 

%d means it reads a decimal integer, not a float .

+4
source

r is a float , but you read it when using %d as the scanf specifier, which expects an int .

+4
source

The real culprit in your code is the scanf("**%d**", &r) line scanf("**%d**", &r) . %d is the format specifier for the integer value since you declared r as a float, then use %f instead of %d .

i.e. scanf("%f", &r)

0
source

Change Either int p, n; float r, si; in int p, n, r; float si;

or change the formatting specifier in scanf ("% d", & r) ; % d to % f .

when you declare r as an integer r = 8 , in this case scanf ("% d", & r); will be accepted. and your program will be compiled and executed.

Both the ad specifier and the format must be the same.

My suggestion is to use %. 2f when working with money. which will give as 10.00, which is the correct format.

0
source

Source: https://habr.com/ru/post/1392784/


All Articles