Floating point character conversion character - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Floating point character conversion character

beinggokulbeinggokul BangalorePosts: 1Member

Hi,

I am no expert in C and I have started learning it again after several years. Excuse me for stupid questions. My question is simple.

When i give %f as conversion character inside printf, but pass some integer to it, what happens? It prints some garbage value? or is there any pattern?

Consider the below program..

#include <stdio.h>
main()
{
float gift1, gift2; 
float total; 
printf("How much do you want to spend on 1 \n");
scanf(" %f", &gift1);
printf("How much do you want to spend on 2 \n");
scanf(" %f", &gift2);
total = gift1+gift2;
printf("\nThe total you will be spending on gifts is $%.2f", total);
printf("\n %s %d %f %c", "Gokul", 90, 100, 'X');
return 0; 
}

In the above program, i have added a final printf which has nothing to do with the rest of the program. I have simply added it. And i have passed the integer 100 to the %f conversion character. While executing the program, i give some random values for gift1,gift2 which accounts to, say 1958.9967. So, total is 1958.9967

But the value of total is also printed as part of my final line, like below

Gokul 90 1958.9967

Here, X is not printed as well. So, what is happening. Instead of 100, when i tried with 100.19, it gives the desired result (like below)

Gokul 90 100.19 X

I tried another small program like below..

#include<stdio.h>
main()
{
printf("\n %f specifies floating number, but i will give an integer",1987);
return 0;
}

Here, my output was like below

0.000000 specifies floating number, but i will give an integer.

Here, where does this 0.000000 comes from? In case of previous program it printed the value of "total" - why? what is the behavior here?

Btw, I am using Code Blocks compiler, if that's of any significance here.

Thanks in advance.

Tagged:

Comments

  • Malcolm_McLeanMalcolm_McLean Posts: 254Member ✭✭

    To understand it, write your own cut-down printf() using varargs. Just support %s, %d and %f. You'll soon see that there is no way of knowing what the user has passed you, other than by looking at the format string. So if he passes you a %f, you have to grab a double from the varargs list. If there's an integer there, it's garbage. It just so happens that that garbage is a very tiny floating point number which %f represents as 0.0000, probably because all the exponent bits are zero.

Sign In or Register to comment.