Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,401 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,121 people online right now. Registration is fast and FREE... Join Now!




Unexpected Output In Structures

 
Reply to this topicStart new topic

Unexpected Output In Structures

aaru_89
27 Sep, 2006 - 08:44 AM
Post #1

New D.I.C Head
*

Joined: 26 Sep, 2006
Posts: 20



Thanked: 1 times
My Contributions
Hello. I am new to C and I was trying to find the answer for the following program to illustrate structures


CODE
#include<stdio.h>
void main()
  {
    struct student{int roll,age;
                        char sex;
                        float height,weight;}
                       s1={101,23,'M',163.2,31.3};
    printf("\n %d %d %c %f %f",s1.roll,s1.age,s1.sex,s1.height,s1.weight);
    getch();
  }



I thought the output would be

101 23 M 163.2 31.3

But what I got while I ran the program was this

101 23 M 163.199997 31.299999

Can someone please explain why this happened. Thanks.
User is offlineProfile CardPM
+Quote Post

Jayman
RE: Unexpected Output In Structures
27 Sep, 2006 - 11:11 AM
Post #2

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 6,985



Thanked: 45 times
Dream Kudos: 500
Expert In: C#, VB.NET, Java

My Contributions
QUOTE(aaru_89 @ 27 Sep, 2006 - 09:44 AM) *

I thought the output would be

101 23 M 163.2 31.3

But what I got while I ran the program was this

101 23 M 163.199997 31.299999

Can someone please explain why this happened. Thanks.


You need to set the precision of your float variables in order to only get 1 number after the decimal point.

CODE
#include<stdio.h>
void main()
  {
    struct student{int roll,age;
                        char sex;
                        float height,weight;}
                       s1={101,23,'M',163.2,31.3};
    printf("\n %d %d %c %.1f %.1f",s1.roll,s1.age,s1.sex,s1.height,s1.weight);
    getch();
  }


Check the following link for info on floats precision.
http://support.microsoft.com/kb/q125056/
User is offlineProfile CardPM
+Quote Post

born2c0de
RE: Unexpected Output In Structures
27 Sep, 2006 - 11:20 AM
Post #3

printf("I'm a %XR",195936478);
Group Icon

Joined: 26 Nov, 2004
Posts: 3,935



Thanked: 34 times
Dream Kudos: 2800
Expert In: 80x86 Assembly, C/C++, VB6, VB.NET, C#, J2SE, Win32 API, Reversing

My Contributions
There's even a programmer joke because of this problem:
QUOTE

2 + 2 = 5 for extremely large values of 2.

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/5/08 03:08AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month