Follow Me on Twitter

Friday, November 6, 2009

Solutions to C Puzzles 8

I thought the following program was a perfect C program. But on compiling, I found a silly mistake.
Can you find it out (without compiling the program :-) ?
#include

void OS_Solaris_print()
{
        printf("Solaris - Sun Microsystems\n");
}

void OS_Windows_print()
{
        printf("Windows - Microsoft\n");

}
void OS_HP-UX_print()
{
        printf("HP-UX - Hewlett Packard\n");
}

int main()
{
        int num;
        printf("Enter the number (1-3):\n");
        scanf("%d",&num);
        switch(num)
        {
                case 1:
                        OS_Solaris_print();
                        break;
                case 2:
                        OS_Windows_print();
                        break;
                case 3:
                        OS_HP-UX_print();
                        break;
                default:
                        printf("Hmm! only 1-3 :-)\n");
                        break;
        }

        return 0;
}
Solution:
Error at void OS_HP-UX_print and OS_HP-UX_print(). The 
function name should not contain "-" as it is invalid.
 
 
What do you think would be the output of the following 
program and why? (If you are about to say "f is 1.0", I 
would say check it out again)
#include 

int main()
{
        float f=0.0f;
        int i;

        for(i=0;i<10;i++)
                f = f + 0.1f;

        if(f == 1.0f)
                printf("f is 1.0 \n");
        else
                printf("f is NOT 1.0\n");

        return 0;
}
 
Solution:
f is NOT 1.0
 
Explanation: The value of f after the loop completion will 
be 1.000000. This is the precision set by the compiler. If 
you want the output as "f is 1.0" replace the if statement 
with if(abs(f - 1.0)==0).
 

No comments:

Post a Comment