Domanda

I seem to have a problem with my use of switch statements in this function, but everything looks correct to me.

    double pricePerUnit(int x, int y)
       double price=pricePerUnit;
       {
       switch(pricePerUnit)
       {
        case '1':
       if(estimatedQuality(x,y)<2)
       {
       price=0.5;
       break;
       }

This is only part of the switch statement, there are a few more cases. The errors however are only for these lines in the code.

    error: parameter âpriceâ is initialized
    error: old-style parameter declarations in prototyped function definition
    error: switch quantity not an integer
    error: âpriceâ undeclared (first use in this function)
    error: (Each undeclared identifier is reported only once
    error: for each function it appears in.)

I am pretty new to C, so this is all kinda confusing to me. If anyone could help, that would be great. Thanks

È stato utile?

Soluzione

You should be testing what estimatedQuality returns, not performing the test before calling it.

double pricePerUnit(int x, int y) {
    int quality = estimatedQuality(x, y);
    double price;
    if (quality < 2) {
        price = 0.5;
    } else if (quality < 4) {
        price = 0.75;
    } else if (quality == 4) {
        price = 1;
    } else if (quality == 5) {
        price = 2;
    }
    return price;
}

You can do it with a switch like this:

double pricePerUnit(int x, int y) {
    double price;

    switch(estimatedQuality(x, y)) {
    case 0:
    case 1:
        price = 0.5;
        break;
    case 2:
    case 3:
        price = 0.75;
        break;
    case 4:
        price = 1;
        break;
    case 5:
        price = 2;
        break;
    }
    return price;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top