【问题标题】:Errors in switch and case statementsswitch 和 case 语句中的错误
【发布时间】:2014-05-03 02:09:39
【问题描述】:

我在这个函数中使用 switch 语句似乎有问题,但对我来说一切都是正确的。

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

这只是switch语句的一部分,还有其他几种情况。然而,错误仅针对代码中的这些行。

    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.)

我对 C 很陌生,所以这对我来说有点困惑。如果有人可以提供帮助,那就太好了。谢谢

【问题讨论】:

  • 您在函数体周围缺少{ }
  • pricePerUnit 是一个函数。为什么要将它分配给应该包含数字的变量?
  • 您希望switch(pricePerUnit) 做什么? pricePerUnit 是一个函数名,不是一个可以与字符'1' 比较的值。
  • 我不知道你想做什么,所以我不能写一个好的答案来说明如何正确地做到这一点。您发布的内容完全没有意义。
  • 不要随意改变事物,您必须了解事物的作用。

标签: c function compiler-errors switch-statement


【解决方案1】:

您应该测试estimatedQuality 返回的内容,而不是在调用它之前执行测试。

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;
}

您可以像这样使用switch 来做到这一点:

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;
}

【讨论】:

  • 感谢您对我的耐心等待!
最近更新 更多