Jump to content

c++ variables?


Corey

Recommended Posts

http://pastie.org/pr...pz00xavctucrvxq

 

 

I made a program that is supposed to be like a coke machine and intake american coins and a dollar bill until a certain amount is reached.

 

It works perfectly when I enter in actual numerical amounts like 0.05 0.25 or 1.00

 

but the way it is supposed to be done from the instructions is I could enter N for nickle and it would store the value of the nickle (0.05) into the variable "amount", but instead it stores something crazy like -9.25596e + 061

 

Instructions of the program -

 

Coke Machine Logic

Implement a coke machine that accepts nickels (N), dimes (D), quarters (Q) and dollar bills (B). Soda costs $0.60 and the machine (your program) should quit accepting coins/bills as soon as at least $0.60 has been entered. The program should output the amount of change the user receives after their purchase.

Link to comment
Share on other sites

Well by defining a constant, you can use N for the nickel in your source code, but not as an input I think.

If you are looking for a straight forwards solution, you could make a switch instruction, where you add the amount for valid input N, D, Q or B and give an error message for all the other inputs.

 

I hope you understand what I am trying to say :P

Link to comment
Share on other sites

I don't know C++ but I know other languages so I guess to understand one is to understand how programming works in general.. pretty sure you'd have to handle the input each time..

 

IE: (this is in a made up language btw)

 

if(coin = n) {

amount = 0.05;

} else if (coin = d) {

amount = 0.10;

} else if (coin = q) {

amount = 0.15; }

else if (coin = B) {

amount = 1.00; }

 

But then I don't really know how the input on your program works.. Obviously if they were simply typing 'N' into a text field then it would be 'n' as a string not the variable 'N' you predefined :P Okay so that's obvious, but not sure whether your method of input (whatever it is) will be doing the same thing >.<

Edited by Chuckun
disabled emoticons
Link to comment
Share on other sites

I have no compiler atm, and it has been a while since i last wrote a c++ program, but the switch instruction is exactly doing this, what chuckun said. The source code for it could look something like this:

 

 

 

 switch (amount)
 {
   case 'n':
   case 'N': total = total + 0.05;
    break;
   case 'd':
   case 'D': total = total + 0.10;
    break;
   case 'q':
   case 'Q': total = total + 0.25;
    break;
   case 'b':
   case 'B': total = total + 1.00;
    break;
   default: cout<<"No valid input."
    break;
 }

 

 

Link to comment
Share on other sites

  • Clan Friend

I know more C than C++ but here is my version: (error corrections appreciated ^^)

maybe it's a bit overcomplicated, and while I was there I could have overloaded all the operators, instead of doing cin>>input; amount = input; but at the end I was getting lazy :D

 

#include <iostream>
#include <sstream>
#include <stdexcept>

using namespace std;


class myDouble
{
double amount;
public:
myDouble() { amount = 0; }
operator double() { return amount; }
friend istream& operator>> ( istream& in, myDouble& x );
};

istream& operator>> ( istream& in, myDouble& x )
{
string tmp;
int i;

struct myValue {
	char name;
	double val;
} values[] = { {'N', 0.05}, {'D', 0.10}, {'Q', 0.25}, {'B', 1.00} };

in>> tmp;

for(i = 0; i < 4;i++)
{
	if(toupper(tmp[0]) == values[i].name)
	{
		x.amount = values[i].val;
		break;
	}
}

if(i == 4)
{
	stringstream ss(tmp);
	if (!(ss >> x.amount).fail()) return in;
	else throw out_of_range ( "Invalid value!" );
}

return in;
}

int main()
{
double amount,refund,total;
myDouble input;

cout<<"Please enter $0.60 to make your purchase "<<endl;
cout<<"N = Nickle, D = Dime, Q = Quarter, B = 1 Dollar Bill"<<endl;

try
{
	cin>>input;
	amount = input;

	while ( amount < .60)
	{
		total = amount;
		cout<<"Entered so far: "<<amount<<" Keep entering change"<<endl;
		cin>>input;
		amount = input;
		amount += total;
	}

	cout<<" Amount entered = "<<amount<<endl;
	refund = amount - .60;
	cout<<"Change = "<<refund<<endl<<endl;
} catch ( out_of_range& ex )
{
	cerr<< ex.what() <<endl;
}
return 0;
}

Link to comment
Share on other sites

  • Clan Friend

a more concise version with a function instead of all that stuff

 

#include <iostream>
#include <sstream>
#include <stdexcept>

using namespace std;

double GetInput(void)
{
   string tmp;
   int i;

   struct myValue {
       char name;
       double val;
   } values[] = { {'N', 0.05}, {'D', 0.10}, {'Q', 0.25}, {'B', 1.00} };

   cin >> tmp;

   for(i = 0; i < 4;i++) {
       if(toupper(tmp[0]) == values[i].name)
           return values[i].val;
   }

   if(i == 4) {
       double amount;
       stringstream ss(tmp);
       if (!(ss >> amount).fail()) return amount;
   }

   throw out_of_range ( "Invalid value!" );
   return 0;
}

int main()
{
   double amount,refund,total;

   cout<<"Please enter $0.60 to make your purchase "<<endl;
   cout<<"N = Nickle, D = Dime, Q = Quarter, B = 1 Dollar Bill"<<endl;

   try
   {
       amount = GetInput();

       while ( amount < .60)
       {
           total = amount;
           cout<<"Entered so far: "<<amount<<" Keep entering change"<<endl;
           amount = GetInput();
           amount += total;
       }

       cout<<" Amount entered = "<<amount<<endl;
       refund = amount - .60;
       cout<<"Change = "<<refund<<endl<<endl;
   } catch ( out_of_range& ex )
   {
       cerr<< ex.what() <<endl;
   }
   return 0;
}

Link to comment
Share on other sites

The problem is not that you're using C++, but two other things.

 

 

 

Everything in the computer is binary. For example, if you're using a short int (char), the number 42 is stored as 0001.1010. A double is a double precision floating point. And a floating point is something different, it's still binary, but you have two parts. One is comparable to the integers, the other is where the point should be (hence, floating point). For example, a 12 bit floating point could store 42 as 1000.0001.1010; the first 4 bit, define where the point is, in this case, on location 8 which is after the 42. If you want to store 6.5, you do the following: 0110.0001.1010. (note, this is easier explained than it really is, for increase of precision you would always want the "integer-part" to have as many numbers as possible, hence, you would always have something like xxxx.1xxx.xxxx except for 0 and the minimum steps above it, that is, 0000.0xxx.xxxx)

 

 

 

Now the problem with floating points (and hence, also with doubles but less fast) is that you cannot define every number. 0.5, 0.25, 0.125 etc are easy to store. But how do you store 0.1? You need to get the 0.675+0.375+..., but eventually you will never reach exactly 0.1. Although you may come close, you never really get it.

 

The solution is therefor to NOT use doubles, but instead of using not-really-correct dollars, the correct cents. As integers :D

 

 

Anyway, another tip:

total = amount;
cout<<"Entered so far: "<<amount<<" Keep entering change"<<endl;
cin>>amount;
amount += total;

is unreadable. What is total? What is amount? I guess amount is the coin inserted, and total is the total sum of coins inserted. So instead, use

cout<<"Entered so far: "<<total<<" Keep entering change"<<endl;
cin>>amount;
total += amount;

Note for this you have to modify lines 26-27 and initialize total=0.

 

 

 

edit-before-send: The actual wrong error :P

 

What you actually do, is also solved in the SunLight explanation: You insert a character "B", but your declaration of "const double B = 1.00;" does not mean that the string "B" in your input is directly translated into the as variable. "B" is data, the B you declared is a variable. It may contain "B", but it's a different entity.

 

The solution as I would do is basicly create a new function

int coinToValue(string coin) {
 if(coin == "B")
return 100;
 if(coin == "Q")
return 25;
 return 0; // this was not a valid coin, ignore, or throw an exception. or whatever.
}

and call that as follows:

string coin;
cin>>coin;
amount = coinToValue(coin);

 

You'll need to #include <string>, but I guess that'll work. If you don't want to include string, or are not allowed to, you'll have to do it a bit harder and use chars, but I guess <string> is perfectly allowed.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.