GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 08-Feb-2006, 07:06
aleminio aleminio is offline
New Member
 
Join Date: Feb 2006
Posts: 3
aleminio is on a distinguished road

Floating Point rounding problems


hi, i have started learning C today.
there is somethnig which is irritating me.
i have this little code: (don't laugh )


CPP / C++ / C Code:
#include <stdio.h>
int main()
{
char men[] = "come and buy";
float kg;
float price =2.2;

printf("today special - %s\n", men);             // just a message
scanf("%f", &kg);                                     // how much kg
printf("you want %f kg.\n", kg);               // printing the kg
printf("that be$%.2f please.\n", price*kg);   // kg*price

int as;                                        // this is just
scanf("%d", &as);                         // to keep the program open      
return (0);                                  //so i can see the result :p
}

how can i make, that the KG i type will count only 2 numbers after the dot?
i mean if i type 2.2343, how can i make that it will count it only as 2.23?
ty, and sorry for my english.
Last edited by aleminio : 08-Feb-2006 at 07:36. Reason: Please enclose c code in [c] ... [/c] tags
  #2  
Old 08-Feb-2006, 07:26
rwehrli
 
Posts: n/a

Re: beginner question.


Quote:
Originally Posted by aleminio
hi, i have started learning C today.
there is somethnig which is irritating me.
i have this little code: (don't laugh )


CPP / C++ / C Code:
#include <stdio.h>
int main()
{
char men[] = "come and buy";
float kg;
float price =2.2;

printf("today special - %s\n", men);             // just a message
scanf("%f", &kg);                                     // how much kg
printf("you want %.2f kg.\n", kg);               // printing the kg
printf("that be $%.2f please.\n", price*kg);   // kg*price

int as;                                        // this is just
scanf("%d", &as);                         // to keep the program open      
return (0);                                  //so i can see the result :p
}

how can i make, that the KG i type will count only 2 numbers after the dot?
i mean if i type 2.2343, how can i make that it will count it only as 2.3?
ty, and sorry for my english.

Wow, if someone wants less than 2.25kg of something, rounding up to 2.3 is surely in the market's favor, don't you think?

Also, modifying "it" so that 2.2343 will count only 2 numbers after the dot will not produce 2.3, but 2.23...perhaps that is what you meant to type?

Just change your printf where you display the kilograms so that the format is similar to your printf where you display the price. Let us know if you really want to change what scanf stored. I modified your code above, so that it will do what I think it is that you want.


Take Care.

Rob!
  #3  
Old 08-Feb-2006, 07:41
aleminio aleminio is offline
New Member
 
Join Date: Feb 2006
Posts: 3
aleminio is on a distinguished road

Re: beginner question.


Yah, i meant 2.23 :>
But listen, i have thought about it, but if i am not wrong, the value stays the same isn't it?
I mean, if i type, 2.234, it will show 2.23
but when it conculate the price, it will still make 2.234 * 2.2. no? :\
  #4  
Old 08-Feb-2006, 08:33
realnapster realnapster is offline
Junior Member
 
Join Date: Feb 2006
Posts: 51
realnapster will become famous soon enough

Re: beginner question.


Mr aleminio you are bit wrong here you was right if input is 2.234 then it wilkl display 2.23 but if the input is 2.236 then it will display 2.24 which is basic mathematics rule that you know think abt it.

You have taken another variable "as" in end just for viewing the output you can do this other way by using any one of following functions

getch()-defined in <conio.h> used to input one value but not echo it on screen

delay(2000) or sleep(2) - defined in <dos.h> used to stp processing for specified time interval delay inputs time in microseconds and sleep inputs normally above mentioned eg will stop for 2 secs

one more question why u wanna input only two digits after decimal because in market there may be any input what's ya reason behind it.
__________________
*Labor omnia consent*** Hardwork conquers all*
  #5  
Old 08-Feb-2006, 09:00
aleminio aleminio is offline
New Member
 
Join Date: Feb 2006
Posts: 3
aleminio is on a distinguished road

Re: beginner question.


if i input 2.236 it will display 2.24.
but then in the end when i calculate the price it will count it as 2.236 * 2.2 instead of 2.24 * 2.2....

I know that this is silly and make no sence, but i am just wondering is there a way to set the variable to have only 2 numbers after the dot already at the input.
without doing that in the output.
And i don't really need it lol, it's just an exercise, i am trying to understand everything.

and thanks for those delay functions, didn't get there yet
  #6  
Old 08-Feb-2006, 09:04
realnapster realnapster is offline
Junior Member
 
Join Date: Feb 2006
Posts: 51
realnapster will become famous soon enough

Re: beginner question.


i will surely answer ya question of restricting the input to 2 digits in the input there is some way and i will give it 2 u very soon just wait for some moments
__________________
*Labor omnia consent*** Hardwork conquers all*
  #7  
Old 08-Feb-2006, 09:10
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,693
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: beginner question.


Quote:
Originally Posted by aleminio
hi, i have started learning C today.

how can i make, that the KG i type will count only 2 numbers after the dot?
i mean if i type 2.2343, how can i make that it will count it only as 2.23?
ty, and sorry for my english.

Most people don't worry about things like rounding until later in their programming careers. I like the idea of doing it sooner.

For calculations involving money, exact answers are usually required. Some decimal numbers, like 1.10 simply cannot be represented exactly as a floating point binary number. Therefore, if you do any floating point arithmetic, you must be aware of the possibility of roundoff error that can affect your results at each step. So the problem is not only rounding off the user input to a two-decimal-digit number, but facing the possibility of having the program introduce floating point errors in storing the value or in any calculations.

Therefore, I suggest that you use integer arithmetic for programs involving dollars and cents (or whatever currency that involves decimal fractions).

In other words, take the user input, multiply by 100 (here is where you do the rounding), and do all calculations in cents. To print out the final result as a decimal number, you still use decimal arithmetic (with integer division and the integer "modulus" operator).

How do you round off a floating point number to an integer?

Here's the usual programmer's trick: add 0.5 to the floating point number and assign to an integer value. So 1.44 becomes 1; 1.54 becomes 2. (Note that 1.5 becomes 2; 2.5 becomes 3, etc. This is not the way that bankers and some mathematicians do it, but I'll stick to programming conventions for now).

Since you indicated that you want to round to the nearest cent before calculating the total cost, you could try something like the following:

CPP / C++ / C Code:
#include <stdio.h>

int main()
{
  float unitprice; /* user entry in dollars  */
  int intprice;    /* price in (rounded)cents */
  int quantity;    /* number of items        */
  int itotal;      /* total in cents         */
  int totaldollars, totalcents;

  printf("Enter a number:  ");
  if (scanf("%f", &unitprice) != 1) {
    printf("Illegal entry: not a number.\n");
  }
  if (unitprice < 0) {
    printf("You entered a negative number.\n");
    return 0;
  }
  intprice = (unitprice * 100.0) + 0.5; /* round and convert to (int)cents */
  printf("Price in cents = %d\n", intprice);
  /* now do calculations in cents */
  quantity = 17;
  itotal = quantity * intprice; /* total in cents */

  totaldollars = itotal / 100;
  totalcents   = itotal % 100;

  printf("Total cost     = $%d.%02d\n", totaldollars, totalcents);

  return 0;
}

Regards,

Dave
  #8  
Old 09-Feb-2006, 04:15
realnapster realnapster is offline
Junior Member
 
Join Date: Feb 2006
Posts: 51
realnapster will become famous soon enough

Re: beginner question.


yes MR.ALEMINIO i have a cool solution for your question regarding that kg. and grams question i m posting a simple code for you just have a look at it and try to work it out
CPP / C++ / C Code:
#include<stdio.h>
int main()
{
   static long a,b,k,l,i;
   float input,temp,result;
   printf("\n enter kg \t");
   scanf("%ld",&a);
   printf("\n enter grams \t");
   scanf("%ld",&b);
   k=b;                         //It is used to calculate the length of grams part
   while(k!=0)
   {
      l++;                      //the length calculates here
      k=k/10;
   }
   for(i=l;i>2;i--)
   {
      b=b/10;                   // rounding off to two decimal places
   }
   temp=(float)b/100;           //conversion in grams
   input=(float)a+temp;         // final input
   result=input*2.25;           // now the cost calculated
   printf("\t %.2f",result);
   return 0;
}

i have supplied enough number of comments in the above question but if still u feel some problems then ask again i will surely try to answer u i am defining something that may boggle ya mind in the example:

while loop is used to calculate the number of digits in the grams

for loop is used for converting grams upto 2 decimal places

(float)--- it is a feature in c language known as type casting which means that the value of the variable is explicitly converted to float only for this statement no change take place in original value

temp stores the value in grams it means somthing like .24

input variable is used to add kg and gram together again typecasting is used

now result is multiplying the input by 2.25 or whatever u want to calculate price.

the code works fine for each value i have used in testing try it yourself

if still you feel some problem then plz post it
__________________
*Labor omnia consent*** Hardwork conquers all*
  #9  
Old 09-Feb-2006, 09:35
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,243
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: beginner question.


Quote:
Originally Posted by realnapster
i will surely answer ya question of restricting the input to 2 digits in the input there is some way and i will give it 2 u very soon just wait for some moments

So how does
CPP / C++ / C Code:
   static long a,b,k,l,i;
   printf("\n enter kg \t");
   scanf("%ld",&a);
   printf("\n enter grams \t");
   scanf("%ld",&b);
restrict "the input to 2 decimals" as you claim? Doesn't this restrict to 0 decimals? This input will not allow 2.354 for KG. And why are you inputting grams? That's not in the original question.

Let's assume, using this program, you enter
Code:
enter kg 2 enter grams 35
What you have is 2.035 KG or 2035 g

aleminio wants to input KG to 2 decimals, not KG and G and find out if G was entered properly.

I will grant your solution is interesting though.
__________________

Age is unimportant -- except in cheese
  #10  
Old 09-Feb-2006, 12:00
realnapster realnapster is offline
Junior Member
 
Join Date: Feb 2006
Posts: 51
realnapster will become famous soon enough

Re: beginner question.


Very sorry to say that my fellow senior member has not understood my code step by step i will request him to go through it step by step otherwise i am ready to post the full functioning of program tommorow as i have to make assignments now i promise you will recieve my post on full functioning of program in my next post tommorow i will also define step by step what's happening there in program ?
__________________
*Labor omnia consent*** Hardwork conquers all*
 
 

Recent GIDBlogMeeting the local Iraqis by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Fresh Small C++ Program :P Sabin044 C++ Forum 40 02-Feb-2006 18:57
ROMAN Numeral Pt. 2, Floating Point Exception SpyD3r C++ Forum 1 13-Nov-2005 00:02
Floating point exception error (Note-long post) crystalattice C++ Forum 16 11-Sep-2004 07:37
Wireless Problems sanctuary71 Computer Hardware Forum 2 11-Jun-2004 08:01
Floating point operand? warny_maelstrom C Programming Language 11 04-Mar-2004 13:31

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 00:46.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.