-3

我不断收到“'rate'在此函数中未初始化”的错误消息。

任何人都可以看到原因吗?我查看了我的代码,并在我的其他函数上正确传递了它,错误源于此函数。有任何想法吗?

double compute_rate(int userAge_array[], char sportType_array[], int index)
{
  double rate;
  if (sportType_array[index] == 'f') {
    if (userAge_array[index] < 25) {
      rate = 68.95;
    }
    else if (userAge_array[index] > 25) {
      rate = 55.95;
    }
  }
  if (sportType_array[index] == 'g') {
    if (userAge_array[index] < 25) {
      rate = 73.95;
    }
    else if (userAge_array[index] > 25) {
      rate = 65.95;
    }
  }
  if (sportType_array[index] == 'h') {
    if (userAge_array[index] < 25) {
      rate = 99.95;
    }
    else if (userAge_array[index] > 25) {
      rate = 92.95;
    }
  }

  return rate;
}
4

3 回答 3

4

rate在函数结束时返回,但它可能永远不会初始化,因为所有赋值都在 ifs 语句中,可能根本不会被处理。

解决方案:

首先使用一些默认值分配它,以防万一没有一个 ifs 起作用:

double rate=0.0;
于 2017-04-26T22:19:52.197 回答
1

如果sportType_array[index]不是'f''g''h',则if不会执行任何块。您应该将这些更改为if/else if,然后else在没有匹配项时添加最后一个子句。

但更有可能的是,问题在于userAge_array[index] == 25。您rate在小于25或大于时设置,但在完全等于时25从不设置。尝试使用而不是,这样你就涵盖了所有情况。rate25elseelse if

double compute_rate(int userAge_array[], char sportType_array[], int index)
{
  double rate;
  if (sportType_array[index] == 'f') {
    if (userAge_array[index] < 25) {
      rate = 68.95;
    }
    else {
      rate = 55.95;
    }
  }
  else if (sportType_array[index] == 'g') {
    if (userAge_array[index] < 25) {
      rate = 73.95;
    }
    else {
      rate = 65.95;
    }
  }
  else if (sportType_array[index] == 'h') {
    if (userAge_array[index] < 25) {
      rate = 99.95;
    }
    else {
      rate = 92.95;
    }
  }
  else {
      rate = 0.0;
  }

  return rate;
}
于 2017-04-26T22:25:21.863 回答
0

如果sportType_array[index]不是 'f'、'g' 或 'h',则该函数直接返回到 return,它在此处返回rate未初始化的 。

如果这些数组中的值不正确,您希望返回什么值?最好设置rate为,即使它不应该发生。

于 2017-04-26T22:20:45.173 回答