printf giving wrong output [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include<stdio.h>
#define square(x) x*x
void main()
{
int i;
i = 8 / square(4);
printf("%d %d", i, 8/square(4));
}
Gives output : 8 8
but if I write below code :
#include<stdio.h>
#define square(x) x*x
void main()
{
float i;
i = 8 / square(4);
printf("%f %f", i, 8/square(4));
}
Gives Output : 8.000000 0.000000
Why like that??? please explain

The problems are not just with the format specifier but also the way you have defined your macro. It should be:
#define square(x) ((x)*(x))
Also macros are not type safe. Now if you cast your results you will see what is happening, since the square of 4 is 16 and 8/16 is 0.5 which gets truncated to int hence becomes 0. For proper values this is how you should typecast:
printf("%d %d", (int)i, (int)(8/square(4)));
printf("\n%f %f", (float)i, (float)8/((float)square(4)));
Sample Output:
0 0
0.000000 0.500000

First of all correct this:
#define square(x) x*x
to
#define square(x) ((x)*(x))
for correct results after macro replacement.
Now, in your first program, as others explained you are using wrong format specifier %f to print an integer (8/(square(4) will evaluate to an integer), which is undefined behavior.
In second program, 8/square(4) is type promoted to float as you are storing the result in float i. Therefore, you get 8.000000 on first printing. On second printing, result is wrong due to same reason as above.

The first is easy to understand so I focus on the second only. You use %f for the second parameter which requires a float number while C compiler take 8/square(4) as integer. This mismatch corrupt your result.

8/square(4) results to an int and trying to print an integer using %f is Undefined behavior. So there is no use of debugging the value you got in second case.
If you are using gcc compiler then command cc -E filename.c may clarify your doubts.

It is because you given float as datatype in second program.
8/square(4) will give an integer result, and hence your output becomes wrong. you used %f to print an integer.
That is so simple...

because %f means the type of number is double and default precision

Related

Expected value not obtained: why? [duplicate]

This question already has answers here:
printf specify integer format string for float
(7 answers)
Closed 5 years ago.
I wrote this very simple and short code, but it doesn't work: when I compile and execute the returned value from the function calculateCharges() is 0 when I'm expecting 2.
Can anybody explain why, please?
#include <stdio.h>
#include <stdlib.h>
float calculateCharges(float timeIn);
int main()
{
printf("%d", calculateCharges(3.0));
return 0;
}
float calculateCharges(float timeIn)
{
float Total;
if(timeIn <= 3.0)
Total = 2.0;
return Total;
}
There are at least three problems here, two of which should be easily noticeable if you enable compiler warnings (-Wall command-line option), and which lead to undefined behavior.
One is wrong format specifier in your printf statement. You're printing a floating point value wirh %d, the format specifier for signed integer. The correct specifier is %f.
The other is using uninitialized value. The variable Total is potentially uninitialized if the if statement in your function isn't gone through, and the behavior of such usage is undefined.
From my point of view, it's likely the wrong format specifier that caused the wrong output. But it's also recommended that you fix the second problem described above.
The third problem has to do with floating point precision. Casting values between float and double may not be a safe round-trip operation.
Your 3.0 double constant is cast to float when passed to calculateCharges(). That value is then cast up to a double in the timeIn <= 3.0 comparison (to match the type of 3.0).
It's probably okay with a value like 3.0 but it's not safe in the general case. See, for example, this piece of code which exhibits the problem.
#include <stdio.h>
#define EPI 2.71828182846314159265359
void checkDouble(double x) {
printf("double %s\n", (x == EPI) ? "okay" : "bad");
}
void checkFloat(float x) {
printf("float %s\n", (x == EPI) ? "okay" : "bad");
}
int main(void) {
checkFloat(EPI);
checkDouble(EPI);
return 0;
}
You can see from the output that treating it as double always is okay but not so when you cast to float and lose precision:
float bad
double okay
Of course, the problem goes away if you ensure you always use and check against the correct constant types, such as by using 3.0F.
%d will print integers.
Total is a float, so it will not work.
You must use the proper specifier for a float.
(You should research that yourself, rather than have us give you the answer)

Sqrt of a floating point number [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Write a C program that asks the user to enter a floating point number from the keyboard and then prints out the square root of that number is the question. What am I doing wrong?
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
double x, result;
printf("Enter a positive number.\n");
scanf("&f", &x);
result = sqrt(x);
printf("The square root of %f is %f.\n", x, result);
return 0;
}
The unary '&' operator delivers the reference (to the operand variable's memory address), while the '%' operator in the context of a scanf or printf, for instance, in conjunction with a particular ANSI C symbols for variable type, such as 'lf' for type double, is known as a format specifier. By placing an integer value between the two, as in '%2lf', one can specify the precision to be read or printed. %f specifies a float type variable, and this achieves lower precision than a double. See the docs too. By the way, in C++, precision is specified otherwise.
So:
double x, result;
printf("Enter a positive number.\n");
scanf("%f", &x); //<--- use %lf (for 'long float' ) instead of &f
Use this
scanf("%lf",&x);
instead of
scanf("&f", &x);

Floating point to string representation [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Consider the following code snippet:
char str[1000];
float b ;
b= 0.0615;
sprintf( &(str[0]), "%1.0e", b);
After the execution of the last statement, I expected the str to contain 6.15e-2. However, I am getting the value as 5e-315.
Where am I going wrong. How to get the expected value?
You cannot get two digits precision with that format string, as you specified only one digit after comma (that is the .0 part after the 1).
What works for me is
#include <stdio.h>
#include <string.h>
main() {
char str[1000];
float b ;
b= 0.0615;
sprintf( &(str[0]), "%.2e", b);
puts(str);
}
prints 6.15e-02
The almighty C/C++ documentation says:
.number:
For a, A, e, E, f and F specifiers: this is the number of digits to be
printed after the decimal point (by default, this is 6).
My bet is you forgot including stdio.h.
There seems to be a mismatch between what type the compiler passes to sprintf and what sprintf actually reads (as described in cmaster's answer).
Apparently your compiler does not realize that sprintf() takes all floating point arguments as doubles. Consequently, it passes only the 32 bits of the float to the function, which erroneously interpretes 64 bits as a double. It should work fine if you cast the float to a double before passing it to sprintf().

Type conversion in Printf [duplicate]

This question already has answers here:
Anomalous behavior of printf()? [duplicate]
(6 answers)
Closed 3 years ago.
The o/p of the code snippet:
printf("%f", 9/5);
in my linux gcc 4.6.3 (gcc myprog.c followed by ./a.out):
-0.000000
in codepad.org:
2.168831
Why the difference?
I have referred the links: Why cast is needed in printf? and Implicit conversion in C?, but could'nt make use of it.
Info regarding codepad execution:
C: gcc 4.1.2
flags: -O -fmessage-length=0 -fno-merge-constants -fstrict-aliasing -fstack-protector-all
EDIT:
More:
for the execution of following in (in same program) codepad
printf("%f\n", 99/5);
printf("%f\n", 18/5);
printf("%f\n", 2/3);
printf("%f\n%f\n%f", 2, 3, 4);
printf("%f\n", 2);
the o/p is
2.168831
2.168831
2.168831
0.000000
0.000000
-0.001246
-0.0018760.000000
The first three outputs are same garbage values (and not the last one). Wondering why.
9/5 is seen as an int .. which leads to undefined output when you use the format specifier %f ( which expects a double )
to print correct result do this:
printf("%f", 9.0/5); // forces system to make sure that the argument is not treates as int
or
printf("%f\n",(double)9/5); // type casting the argument to a double .. this is more helpful
// in case you have a variable
I am not sure how codepad.org compiles their code .. but for gcc you have to have correct arguments for the printf to match with the format specifier
Consider the following to see this more carefully:
#include <stdio.h>
int main(){
printf("%f %d %f\n",9/5,9/5,9.0/5);
printf("%f\n",1); // as suggested by devnull-again since the argument is not a double
// the output is undefined
return 0;
}
Output:
$ ./test
0.000000 1 1.800000
0.000000
It's undefined behavior, anything could be printed at all. 9/5's type is int. %f requires a double to be passed (if you pass a float, it will be converted to double thanks to automatic promotion of arguments to variadic function calls, so that's ok too).
Since you're not giving a double, anything can happen.
In practice, assuming sizeof(int)==4 and sizeof(double)==8, your printf call will read 4 bytes of random garbage. If that's all zeros, then you'll print zero. If it's not, you'll print random stuff.
Codepad is wrong.
Every number is int if stated otherwise - that is the key to solution.
In C/C++ 9/5 is int number and equals 1
That is why your :
printf("%f\n", 9 / 5);
is the same as:
printf("%f\n", 1);
But why it prints 0.0 you ask - here is why.
When printf is given '%f' flag it will treat a parameter as float.
Now your code disassembly looks / may look like that:
printf("%f\n", 9 / 5);
push 1
call dword ptr [__imp__printf (0B3740Ch)]
push 1 moves (usually 32bit 0x1) on the stack
And now the most important how 32 bit value=1 looks (in binary):
(MSB) 00000000 00000000 00000000 00000001 (LSB)
and what this pattern means if treated as 32 bit floating point (according to this):
sign(bit #31) = 0
exponent(next 8 bits ie #30..#23) all = 0 too
fraction(the remaining bits) contains 1(dec)
This is in theory BUT exponent=0x0 which is special case (read link) and is treated as 0.0 - period.

format string in printf [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the output?
main()
{
float a=4;
int i=2;
printf("%f %d",i/a,i/a);
printf("%d %f",i/a,i/a);
}
The answer I'm receiving is: 0.500000 00 0.000000
Reason: In the first printf, %f=i/a=2/4=int/float so the implicit casting is done and i becomes float which causes a result of a float (i.e 0.500000).
Default precision of float is 6 so after decimal 6 digit then next %d=i/a=2 /4=0.500000, but %d format string print only integer so 0 is printed and after decimal values are discarded.
Next printf with %d=i/a=2/4 print 0 has the same concept; however, %f=i/a=2/4=0.000000 last result I did not understand.
This plain undefined behavior to specify the wrong format specifier to printf in both cases the i/a expression will be promoted to double and you are specifying that it is a int for one argument. The C99 draft standard in section 7.19.6.1 The fprintf function which printf's section refers back to for the format string paragraph 9 says:
If a conversion specification is invalid, the behavior is undefined.[...]
You should enable warning but both gcc and clang will warn about this without cranking them up at all, in gcc I obtain the following message:
warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat]
i/a expression will always evaluate to float since one of the operands are float. While printing, we are using specifiers %d and %f. So when we use %f it will (should) always be 0.5 and when we use %d it should be undefined.
On Linux (ubuntu) with gcc compiler I get following output (added a \n after first print for clarity):
0.500000 2047229448
899608576 0.500000
Undefined behaviour: all the data types in printf are implicitly floats. This is because i/a has type float as the int datum gets promoted to floating point. So you must use %f exclusively in your printf.

Resources