-3

im trying to execute this script its for my university

int main()
{
int x;
double y;

Provo:
cout<<"Vlera e X: ";
cin>>x;
switch(x)
{
    case ((x)<(0.9)):
        y=x*x;
        break;
    case (x==0.9):
        y=2*x;
        break;
    case 'x>0.9':
        y=x-3;
        break;
}   
cout<<"\n\n";
return 0;
}

this is teh code and the error is:

17  10  ....\Untitled1.cpp  [Error] 'x' cannot appear in a constant-expression

someone help please?

  • 6
    Switch cases need compile-time constants. You can't base them off of user input. What you really need from the start is if-else. Switches only do equality. – chris Oct 26 '13 at 16:32
  • 1
    Use if else instead. Also, x is an int and will never equal 0.9. – Mark PM Oct 26 '13 at 16:32
  • 1
    Also, x is an int so it will never be == 0.9; it could be bigger or smaller only – Jmc Oct 26 '13 at 16:33
  • Yes, in the C-based languages you cannot have case statements with `> <` tests -- they must be exactly equal. I'm vaguely recalling that Modula or Pascal supports `> <` tests. – Hot Licks Oct 26 '13 at 16:35
  • Your last (3rd) case statement has single quotes... for no good reason. And you have a label, `Provo` that suggests you've thought about [goto](http://imgs.xkcd.com/comics/goto.png). [What is this?](http://files.sharenator.com/picard-s300x266-70882.jpg) – abelenky Oct 26 '13 at 17:13

1 Answers1

3

I think you have misunderstood how to use the switch statement. switch is used to branch your code based on the condition, in your case x, taking different integral values. It is not suitable for use with double values like you do.

A correct switch expression would look like:

switch(x)
{
case 1:
    y=x*x;
    break;
case 2:
case 3:
case 4:
    y=2*x;
    break;
case 5:
    y=x-3;
    break;
}   

To accomplish what you want, use if else instead, for example:

if (x < 0.9) {
    y=x*x;
else if(x == 0.9) {
    y=2*x;
} else {
    y=x-3;
}   

However, comparing floating point values for equality is a bad idea. It is usually better to do something like:

double epsilon = <some small value>;
if (x < 0.9-epsilon) {
    y=x*x;
else if(x > 0.9+epsilon) {
    y=x-3;
} else {
    y=2*x;
}
Community
  • 1
  • 1
Krumelur
  • 31,081
  • 7
  • 77
  • 119