# switches with doubles?

## Recommended Posts

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[i] >= 0 ) && ( dGrade[i] <= 100 )){

break;
break;
break;
break;
break;
}
}
}

or... how would be the easiest way to do this ??

##### Share on other sites
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[i] > 50)	cGrade[i] = F;else if ((dGrade[i] <= 50) && (dGrade[i] < 60))	cGrade[i] = D;else if ((dGrade[i] <= 60) && (dGrade[i] < 70))	cGrade[i] = C;else if ((dGrade[i] <= 70) && (dGrade[i] < 80))	cGrade[i] = B;else if ((dGrade[i] <= 90) && (dGrade[i] < 100))	cGrade[i] = A;

##### Share on other sites
Quote:
 Original post by AgonyI 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.

##### Share on other sites
Quote:
Original post by snk_kid
Quote:
 Original post by AgonyI 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.]

##### Share on other sites
You really need to learn to get < and > the right way around...
> 50 gives you F ???
<=50 AND < 60 gives you D ???

Using dGrade[i] divided by ten will vastly simplify the rest of your code...
			switch(dGrade[i] / 10) {				case 6:					cGrade[i] = 'D';					break;				case 7:					cGrade[i] = 'C';					break;				case 8:					cGrade[i] = 'B';					break;				case 9:					cGrade[i] = 'A';					break;				default:					cGrade[i] = 'F';			}

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628349
• Total Posts
2982210

• 10
• 9
• 24
• 11
• 9