for which value of f, the output will be "world"?
#include<stdio.h>
int main(){
float f= ... ;
if(f==f)
printf("hello\n");
else
printf("world\n");
return 0;
}
what will be replaced with three dots (...)
Try this:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
float f = nanf("0.0");
printf("%f\n", f);
if(f==f)
printf("hello\n");
else
printf("world\n");
return 0;
}
Easy.
float f = (puts("world"), exit(0), 0.0f);
Edit: Yes, I know you're looking for a different answer. But I'm going to be cute instead because this looks like a problem from a homework assignment or take-home quiz that hasn't even been broken down into its parts.
IEEE 754 floating point numbers can represent positive or negative infinity
and NaN
(not a number). These 3 values arise from calculations whose result is undefined or cannot be represented accurately. NaN
will always propagate through expressions. ie any expression containing NaN
will evaluate NaN
.
You can also deliberately set a floating-point variable to NaN
. For example, the following perfectly valid floating-point expression will do the trick :
sqrtf(-1.0f) // NaN
More info on infinity and NaN in floating point numbers .
PS: I was tempted to ignore this as it looks like a straightforward homework Q. But what with the homework tag being deprecated and all...
You can use the NAN
macro from math.h
.
#include <math.h>
#include <stdio.h>
int main(void)
{
float f = NAN;
if (f == f)
printf("hello\n");
else
printf("world\n");
}
Note that this macro has been introduced in C99 and is not present if the implementation does not support quiet NaNs for the float
type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.