Sign in to follow this  
Surg AKA Kunark

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 )){
			cout << dGrade[i] << "\n";

			switch(dGrade[i]) {
				case (dGrade[i] > 50):
					cGrade[i] = F;
					break;
				case ((dGrade[i] <= 50) && (dGrade[i] < 60)):
					cGrade[i] = D;
					break;
				case ((dGrade[i] <= 60) && (dGrade[i] < 70)):
					cGrade[i] = C;
					break;
				case ((dGrade[i] <= 70) && (dGrade[i] < 80)):
					cGrade[i] = B;
					break;
				case ((dGrade[i] <= 90) && (dGrade[i] < 100)):
					cGrade[i] = A;
					break;
			}
		}
	}
or... how would be the easiest way to do this ??

Share this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.]

Share this post


Link to post
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';
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this