473,406 Members | 2,698 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

quick help for weird problem.

Can someone tell me why I'm having this problem:
When I select drink 5 and deposit too little money, there's a problem
with the 'difference' variable. Try to deposit $.80 instead of the
full $.85 and see what happens if you then keep entering .01 until you
have added the full .85. The program still asks the user to deposit
$0.00. It is telling me for some reason that 0.850000 - 0.850000 =
5.96046e-008.
Any suggestions?

/*
machine.txt:
------------------
Cola
0.75 20
Ruby Red Blast
1.00 10
Lemon Fizz
0.75 8
Grape Soda
0.90 5
Citrus Flip
0.85 0
Habanero Surprise
0.80 11
-------------------
*/

/* ================================================== ============== */
#include <stdio.h>
#include <string.h>
#include <math.h>
/* ================================================== ============== */
#define MAXNUMDRINKS 6
#define STRINGSIZE 25
#define noGood 0
/* ================================================== ============== */

typedef char String [STRINGSIZE];
typedef enum bool { false, true } bool;

typedef struct drinkRec
{
String brand;
float price;
int quantity;
} drinkRec;

typedef drinkRec drinkList [ MAXNUMDRINKS ];

/* ================================================== ============== */

void ReadAllDrinks ( int* numDrinks, drinkList drinks );
void PrintDrinkMenu (int* menuChoice, int numDrinks, drinkList
drinks);
void GetNewQuantity (int menuChoice, drinkList drinks);
void GetMoney (int menuChoice, drinkList drinks);

/* ================================================== ============== */

int main ( )
{
drinkList drinks;
int numDrinks, menuChoice;
double profit = 0;
printf ("Welcome to the Soda Machine.\n");
ReadAllDrinks ( &numDrinks, drinks );
do
{
PrintDrinkMenu (&menuChoice, numDrinks, drinks);
if (menuChoice != 0){
GetMoney (menuChoice, drinks);
if (drinks[(menuChoice - 1)].quantity > 0)
profit = profit + .25;
GetNewQuantity (menuChoice, drinks);
}
}
while (menuChoice != 0);
printf("\n%s%.2f\n","Current Run's Profit: $", profit);
printf("\nBYE BYE\n\n");
return ( 0 );

}
/* ================================================== ============== */

void ReadAllDrinks(int *numDrinks, drinkList drinks)
{
String dummy;
float dummy2 = 0;
char *line;
FILE *inFile;
int count = 0;
if ((inFile = fopen("machine.txt", "r"))) {
while ((line = fgets(drinks[count].brand, STRINGSIZE, inFile))) {
drinks[count].brand[strlen(drinks[count].brand) - 1] = '\0';
fscanf(inFile, "%f%d",
&drinks[count].price,&drinks[count].quantity);
fgets(dummy, STRINGSIZE, inFile);
count++;
}
*numDrinks = count;
fclose(inFile);
}
else printf( "machine.txt not read\n");
}
/* ================================================== ============== */
void PrintDrinkMenu (int* menuChoice, int numDrinks, drinkList drinks)
{
int count, result;
String dummy;
printf("\n Drink Price Amount Left");
printf("\n ------------- ----- -----------\n");
for (count = 0; count < numDrinks; count++){
printf("%d. %-19s$%4.2f", (count + 1),
drinks[count].brand,drinks[count].price);
if (drinks[count].quantity < 1)
printf(" %8s","SOLD OUT\n");
else
printf(" %8d\n",drinks[count].quantity);
}
printf("\n0. Exit\n");
do
{
printf("\nPlease enter your selection: ");
result = scanf("%d", menuChoice);
if (result == noGood) /* This error checks for any input other
than an integer*/
scanf("%s", &dummy); /* If input is non-integer, force scanf to
stop looping */
}
while ((*menuChoice > numDrinks) || (*menuChoice < 0)|| (result ==
noGood));
}
/* ================================================== ============== */
void GetNewQuantity (int menuChoice, drinkList drinks)
{
int prevQuantity;
prevQuantity = drinks[(menuChoice - 1)].quantity;
drinks[(menuChoice - 1)].quantity = prevQuantity - 1;
}
/* ================================================== ============== */
void GetMoney (int menuChoice, drinkList drinks)
{
int result;
String dummy;
float moreMoneyIn, moneyIn, difference;
if (drinks[menuChoice - 1].quantity > 0){
do
{
printf("\n%s%.2f: $","Please deposit $",drinks[menuChoice -
1].price );
result = scanf("%f",&moneyIn);
if (result == noGood) /* This error checks for any input other
than an float*/
scanf("%s", &dummy); /* If input is non-float, force scanf to
stop looping */
}
while (result == noGood);
printf("\n%s$%.2f\n","You put in ",moneyIn);
difference = (drinks[menuChoice - 1].price) - moneyIn;
while (difference != 0){
if (difference > 0){
do
{
printf("%s%.2f: ","Please deposit an additional $",
fabs(difference));
result = scanf("%f", &moreMoneyIn);
if (result == noGood) /* This error checks for any input
other than an float*/
scanf("%s", &dummy); /* If input is non-float, force scanf
to stop looping */
}
while (result == noGood);
printf("\n%s$%.2f.\n","You put in ",moreMoneyIn);
moneyIn = moneyIn + moreMoneyIn;
difference = ((drinks[menuChoice - 1].price) - moneyIn);
}
if (difference < 0){
printf("%s%.2f","Your change is $", fabs(difference));
difference = 0;
}
}
printf("\n\nThank you, money accepted. Enjoy your drink!\n");
}
else printf("\n%s %s\n",drinks[menuChoice - 1].brand, "is sold out.
Please choose another.");
}
Nov 14 '05 #1
4 1721

"Jeffrey Barrett" <on*********@hotmail.com> wrote

Can someone tell me why I'm having this problem:
When I select drink 5 and deposit too little money, there's a problem
with the 'difference' variable. Try to deposit $.80 instead of the
full $.85 and see what happens if you then keep entering .01 until you
have added the full .85. The program still asks the user to deposit
$0.00. It is telling me for some reason that 0.850000 - 0.850000 =
5.96046e-008.
Any suggestions?
The amount 0.01 has no exact binary representation. In effect you have a
small random error whenever you calculate a multiple of such an amount,
hence the tiny difference in your subtraction.

The solution is to store the monetary value as an amount of pennies / cents,
and then just convert to dollars immediately before output to the user.

Nov 14 '05 #2
[snips]

On Fri, 30 Jul 2004 15:50:32 -0700, Jeffrey Barrett wrote:
Can someone tell me why I'm having this problem:
When I select drink 5 and deposit too little money, there's a problem
with the 'difference' variable. Try to deposit $.80 instead of the
full $.85 and see what happens if you then keep entering .01 until you
have added the full .85. The program still asks the user to deposit
$0.00. It is telling me for some reason that 0.850000 - 0.850000 =
5.96046e-008.
Any suggestions?


Yeah; don't use floats/doubles. What you're seeing, apparently, is the
following: instead of storing 0.85 exactly (in at least one case) it's
storing a value something like 0.8500000059604. Since the two aren't the
same, any comparison that assumes they should be will fail.

Simplest answer: use integer types and scale on I/O. That is, instead of
storing 0.85 dollars, store 85 cents and, if you need to, display it as
0.85 dollars.
Nov 14 '05 #3
On Fri, 30 Jul 2004, Jeffrey Barrett wrote:
Can someone tell me why I'm having this problem:
When I select drink 5 and deposit too little money, there's a problem
with the 'difference' variable. Try to deposit $.80 instead of the
full $.85 and see what happens if you then keep entering .01 until you
have added the full .85. The program still asks the user to deposit
$0.00. It is telling me for some reason that 0.850000 - 0.850000 =
5.96046e-008.
Any suggestions?
The problem is floating point numbers. There is a thing called
representation error. Think about this, in pure mathematics there are
infinite fractions between the numbers 0 and 1. Since a computer has
finite amounts of storage it cannot represent all real numbers. The way it
works is that there are gaps. Different systems will have different gaps.
You system does not use 0.01. It will round it up or down to some other
value.

Because you can never be sure what numbers the floating point
implementation your system uses, you are best to use integers. You know
that you want to represent a finite set of values. Use an algorithm that
is very straight forward. For example,

int money;

money = 1; /* $0.01 */
money = 85; /* $0.85 */
money = 125; /* $1.25 */

When you go to print it to the user you would use:

printf("$%d.%02.2d\n", money/100, money%100);
/*
machine.txt:
------------------
Cola
0.75 20
Ruby Red Blast
1.00 10
Lemon Fizz
0.75 8
Grape Soda
0.90 5
Citrus Flip
0.85 0
Habanero Surprise
0.80 11
-------------------
*/

/* ================================================== ============== */
#include <stdio.h>
#include <string.h>
#include <math.h>
/* ================================================== ============== */
#define MAXNUMDRINKS 6
#define STRINGSIZE 25
#define noGood 0
/* ================================================== ============== */

typedef char String [STRINGSIZE];
typedef enum bool { false, true } bool;

typedef struct drinkRec
{
String brand;
float price;
int quantity;
} drinkRec;

typedef drinkRec drinkList [ MAXNUMDRINKS ];

/* ================================================== ============== */

void ReadAllDrinks ( int* numDrinks, drinkList drinks );
void PrintDrinkMenu (int* menuChoice, int numDrinks, drinkList
drinks);
void GetNewQuantity (int menuChoice, drinkList drinks);
void GetMoney (int menuChoice, drinkList drinks);

/* ================================================== ============== */

int main ( )
{
drinkList drinks;
int numDrinks, menuChoice;
double profit = 0;
printf ("Welcome to the Soda Machine.\n");
ReadAllDrinks ( &numDrinks, drinks );
do
{
PrintDrinkMenu (&menuChoice, numDrinks, drinks);
if (menuChoice != 0){
GetMoney (menuChoice, drinks);
if (drinks[(menuChoice - 1)].quantity > 0)
profit = profit + .25;
GetNewQuantity (menuChoice, drinks);
}
}
while (menuChoice != 0);
printf("\n%s%.2f\n","Current Run's Profit: $", profit);
printf("\nBYE BYE\n\n");
return ( 0 );

}
/* ================================================== ============== */

void ReadAllDrinks(int *numDrinks, drinkList drinks)
{
String dummy;
float dummy2 = 0;
char *line;
FILE *inFile;
int count = 0;
if ((inFile = fopen("machine.txt", "r"))) {
while ((line = fgets(drinks[count].brand, STRINGSIZE, inFile))) {
drinks[count].brand[strlen(drinks[count].brand) - 1] = '\0';
fscanf(inFile, "%f%d",
&drinks[count].price,&drinks[count].quantity);
fgets(dummy, STRINGSIZE, inFile);
count++;
}
*numDrinks = count;
fclose(inFile);
}
else printf( "machine.txt not read\n");
}
/* ================================================== ============== */
void PrintDrinkMenu (int* menuChoice, int numDrinks, drinkList drinks)
{
int count, result;
String dummy;
printf("\n Drink Price Amount Left");
printf("\n ------------- ----- -----------\n");
for (count = 0; count < numDrinks; count++){
printf("%d. %-19s$%4.2f", (count + 1),
drinks[count].brand,drinks[count].price);
if (drinks[count].quantity < 1)
printf(" %8s","SOLD OUT\n");
else
printf(" %8d\n",drinks[count].quantity);
}
printf("\n0. Exit\n");
do
{
printf("\nPlease enter your selection: ");
result = scanf("%d", menuChoice);
if (result == noGood) /* This error checks for any input other
than an integer*/
scanf("%s", &dummy); /* If input is non-integer, force scanf to
stop looping */
}
while ((*menuChoice > numDrinks) || (*menuChoice < 0)|| (result ==
noGood));
}
/* ================================================== ============== */
void GetNewQuantity (int menuChoice, drinkList drinks)
{
int prevQuantity;
prevQuantity = drinks[(menuChoice - 1)].quantity;
drinks[(menuChoice - 1)].quantity = prevQuantity - 1;
}
/* ================================================== ============== */
void GetMoney (int menuChoice, drinkList drinks)
{
int result;
String dummy;
float moreMoneyIn, moneyIn, difference;
if (drinks[menuChoice - 1].quantity > 0){
do
{
printf("\n%s%.2f: $","Please deposit $",drinks[menuChoice -
1].price );
result = scanf("%f",&moneyIn);
if (result == noGood) /* This error checks for any input other
than an float*/
scanf("%s", &dummy); /* If input is non-float, force scanf to
stop looping */
}
while (result == noGood);
printf("\n%s$%.2f\n","You put in ",moneyIn);
difference = (drinks[menuChoice - 1].price) - moneyIn;
while (difference != 0){
if (difference > 0){
do
{
printf("%s%.2f: ","Please deposit an additional $",
fabs(difference));
result = scanf("%f", &moreMoneyIn);
if (result == noGood) /* This error checks for any input
other than an float*/
scanf("%s", &dummy); /* If input is non-float, force scanf
to stop looping */
}
while (result == noGood);
printf("\n%s$%.2f.\n","You put in ",moreMoneyIn);
moneyIn = moneyIn + moreMoneyIn;
difference = ((drinks[menuChoice - 1].price) - moneyIn);
}
if (difference < 0){
printf("%s%.2f","Your change is $", fabs(difference));
difference = 0;
}
}
printf("\n\nThank you, money accepted. Enjoy your drink!\n");
}
else printf("\n%s %s\n",drinks[menuChoice - 1].brand, "is sold out.
Please choose another.");
}


--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@whitehouse.gov
Nov 14 '05 #4
"Jeffrey Barrett" <on*********@hotmail.com> wrote:
Can someone tell me why I'm having this problem:
When I select drink 5 and deposit too little money, there's a problem
with the 'difference' variable. Try to deposit $.80 instead of the
full $.85 and see what happens if you then keep entering .01 until you
have added the full .85. The program still asks the user to deposit
$0.00. It is telling me for some reason that 0.850000 - 0.850000 =
5.96046e-008.
Any suggestions?


Yeah, no need to even read your program. The problem is that, of the numbers
0.80, 0.85 and 0.01, none of them can be represented exactly in a binary
floating point system. The solution to your problem is to represent all
values as a whole number of cents. Don't bother with floating point, just
use an int.

Then you can use a printf format like this:
printf("$%d.%02d", price / 100, price % 100);

--
Simon.
Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: redneck_kiwi | last post by:
Hi all: I have a really weird problem. I am developing a customer catalog system for my company and as such have delved into sessions for authentication and access levels. So far, I have managed...
13
by: Wolfgang Kaml | last post by:
Hello All, I have been researching newsgroups and knowledgebase all morning and not found a solution that would solve the problem I have. I am having an ASP or ASPX web page that implement a...
1
by: Kaneda | last post by:
Hello everyone! I have some weird(?) problems, and I am not quite sure if there are due to my errors or maybe a limitation in the .Net framework. I have a ComboBox I need to fill with the...
0
by: Kaneda | last post by:
Hello everyone! I have some weird(?) problems, and I am not quite sure if there are due to my errors or maybe a limitation in the .Net framework. I have a ComboBox I need to fill with the...
6
by: Unicorn | last post by:
I can only say this is a weird problem! I will be sitting there typing away in the code window, when the whole IDE just vanishes without a trace. I get no error messages and no indication, it...
0
by: Zwyatt | last post by:
having a really weird little bug w/ time_t...check it out: I have the following code (simplified here): #include <time.h> class A { public: char *aString; int aNum;
1
by: Strange Cat | last post by:
Hi everyone! I have a weird problem with FormsAuthentication. I have an app that works just fine with FormsAuthentication. The user requests the homepage, he is redirected to login page,...
12
by: Ron Weldy | last post by:
I have a test server runinng 2003/IIS 6 with a mixture of asp and asp.net files. On my workstation I have a share set up to the folder where the web files reside. I am just doing quick and dirty...
3
by: Johannes | last post by:
Hi, I got a strange prblem when using InnoSetup to deploy an EXE made with VB6 on WinXP: If I run the setup the ABC.EXE is installed without problems. But when I start the ABC.EXE it is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.