Can't use the varible two times?

Started by
4 comments, last by Kilom 15 years, 3 months ago
I was just messing around, creating small things with C++, when I tried to do this
unsigned int formula = userVal*3.14/(userVal*666);
I'm guessing you're not allowed to do that? At least not in the way I wanted it to? No matter what number I enter, the result is the same, unless I change one of the other values in the "formula". And if I get rid of the second userVal, and replace it with a regular integer, everything works out fine. So yeah, not allowed (well considering it doesn't error out on compile...), or just not able to actually do it? Is there a way to get around this? I would Google it...but I honesty have no idea what I should search for. Thanks. For some reason I feel this may not be the most correct section for this...but oh well.
Advertisement
The problem with userVal*3.14/(userVal*666), is that it the same as (userVal/userVal)*(3.14/666), which is just 3.14/666. Unless userVal is 0, which means you'll cause a divide-by-zero and get NaN back.

Also 'formula' is only an unsigned int, so the floating point part of that expression will be discarded and you'll just get 0 every time.
Post the whole function.
Sorry, but that is completly valid, and will return an answer, so i assume there is something else missing from the equation.

The other posibility (considering the 3.14) is that you are experiencing a problem because userVal is an int. Due to how C++ promotes value types you may not get what you expected.

int*float / (int * int) >> int * int / (int * int)
float * int / (float * int) >> float * float / (float * float)

try making everything there a float, and see if you get better answers.

and userval / userval => 1. so that doesnt help.
Well here's the whole thing (was just messing around with the arithmetic operators),

void main(){	cout << "Enter a number and I'll do a wacky formula to it!\n";	cout << ">";	float userVal;	cin >> userVal;	float formula = userVal*3.14/(userVal*666);	cout << formula;	system("pause");}


I changed both types to float (like above), but yet same problem arises, just this time it's coming out to 0.00471471 instead of 0 (yeah because it's no longer discarding the floating point)

Is this something I should avoid doing?

EDIT: Sorry for not seeing your post, hh10k, but you're right. Just generally bad placement of an operator on my part. Well I did throw something randomly together for it. Thanks for the help anyways.
as hh10k pointed out n / n = 1. and 1 * m = m. so your formula just cancels out userVal, thus you don't see any effect.

change your formula to something more interesting

userVal * 3.14 + 1.0 / (userVal * 555)
Yeah, I'm just an idiot :)

This topic is closed to new replies.

Advertisement