switches with doubles?

Started by
3 comments, last by iMalc 19 years, 5 months ago
Okay i just got newbed by c++ .... is there a way to use doubles with a switch? I had this...

	for(int i=23; i>=0; i--) {

		cout.setf(ios::fixed);
		cout.precision(1);

		if (( dGrade >= 0 ) && ( dGrade <= 100 )){
			cout << dGrade << "\n";

			switch(dGrade) {
				case (dGrade > 50):
					cGrade = F;
					break;
				case ((dGrade <= 50) && (dGrade < 60)):
					cGrade = D;
					break;
				case ((dGrade <= 60) && (dGrade < 70)):
					cGrade = C;
					break;
				case ((dGrade <= 70) && (dGrade < 80)):
					cGrade = B;
					break;
				case ((dGrade <= 90) && (dGrade < 100)):
					cGrade = A;
					break;
			}
		}
	}
or... how would be the easiest way to do this ??
~~Johnathan~~LTM my new fad, know it, use it, love it, LAUGHING TO MYSELF
Advertisement
I assume double constants would work, but C/C++ switches in no way allow ranges. You'll have to use if/else statements:
if (dGrade > 50)	cGrade = F;else if ((dGrade <= 50) && (dGrade < 60))	cGrade = D;else if ((dGrade <= 60) && (dGrade < 70))	cGrade = C;else if ((dGrade <= 70) && (dGrade < 80))	cGrade = B;else if ((dGrade <= 90) && (dGrade < 100))	cGrade = A;
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
Quote:Original post by Agony
I assume double constants would work


switch statements accept integral types only or user defined type for which there is an unambiguous conversion to integral type.
Quote:Original post by snk_kid
Quote:Original post by Agony
I assume double constants would work


switch statements accept integral types only or user defined type for which there is an unambiguous conversion to integral type.

Gotcha. Even I was being too liberal with my assumptions. Thanks for the correction.

[I suppose I could've easily looked it up in the docs, but, meh, I'm in a weird mental funk today, and I wanted to beat everyone else to an answer so I could stay in the top 20 ranked non-mods/staff. [smile] I'm silly, I know.]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
You really need to learn to get < and > the right way around...
> 50 gives you F ???
<=50 AND < 60 gives you D ???

Using dGrade divided by ten will vastly simplify the rest of your code...
			switch(dGrade / 10) {				case 6:					cGrade = 'D';					break;				case 7:					cGrade = 'C';					break;				case 8:					cGrade = 'B';					break;				case 9:					cGrade = 'A';					break;				default:					cGrade = 'F';			}
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement