Small C+ Question

Odigo

Gawd
Joined
Apr 22, 2002
Messages
805
I'm creating a console application where you input a selection number (example: How many Apples do you want? Each cost $5.). I have everything working fine, and calculations are correction.. I'm using :
double Apple, Grapes, Total;

To calculate I'm doing:
Total = Apple * 5 + Grapes * 2;

While this works, I'm not sure if there is a better way to do this? It's a small program so this may be good enough.
 
I would use int or long to represent a quantity of discrete items (or long long for lots of them!). When you shop, for example, you can buy 5 apples, but not 5.333 apples. While it shouldn't make a difference in calculation here (the result is promoted to a double, anyway), it should make your app more robust (if that's the right term) if you aren't loosely throwing around doubles or floats as operands in comparison expressions.
 
Last edited:
Unless I missed something, that looks like it's as simple as it can get. Although I would also go the int route rather than double since you aren't dealing with cents, or are you?
 
No cents.. how do I go about calculation for int? The same way, just instead of double use int?
 
No cents.. how do I go about calculation for int? The same way, just instead of double use int?
Just use them in the same expression. Since the end result is a double, all values in the expression are automatically promoted to double. You'll find trouble, though, if your end result was an int and you were using floats or doubles in the expression, as the end result is truncated.
 
I'm not sure if there is a better way to do this?

There's always a better way. Here are some super-subtle tweaks that become relevant when you expect code to live more than a few days:

C99 and C++ allow you to postpone declarations until you need them.
const FTW.

Instead of:
double Apple, Grapes, Total;
/* ... */

/* Read in "Apples" */

/* Read in "Grapes" */

/* ... */

Total = Apple * 5 + Grapes * 2;

consider:


int Apples = -1;
int Grapes = -1;
/* ... */

/* Read in "Apples" */

/* Read in "Grapes" */

/* ... */

const double TOTAL = Apple * 5 + Grapes * 2;
 
Back
Top