用C ++总计得分

时间:2014-04-05 18:54:40

标签: c++

好的,所以当我运行这段代码时,我得到的是我的总数等于0 搞砸了我的平均水平和成绩。我不确定我做错了什么 总计+ =得分函数是它应该的位置,但它仍然没有加起来 分数。

int validateNumber(int, int, int);

main()函数

int num, score, total = 0;

validateNumber(num, score, total);

和定义

int validateNumber(int num, int score, int total) {
  while (num < 1 || num > 4) {
    cout << over3 << num << " is not between 1 and 4! Try again: ";
    cin >> num;
  }
  system("CLS");
  for (int i = 1; i <= num; i++) {
    cout << over3 << "Enter score " << i << ": " << endl;
    cout << over3 << "Enter a value from 0 to 100: ";
    cin >> score;
    while (score < 0 || score > 100) {
      cout << over3 << score
           << " is not between 0 and 100! Renter the score: " << i << ": ";
      cin >> score;
    }
    total += score;
  }
  return total;
}

2 个答案:

答案 0 :(得分:1)

如果您想像在此处一样实施validate()功能,

validateNumber(num,score,total);

您可以将其设为void并传递变量total作为参考。 e.g,

void validateNumber(int num, int score, int &total) {
  while (num < 1 || num > 4) {
    cout << over3 << num << " is not between 1 and 4! Try again: ";
    cin >> num;
  }
  system("CLS");
  for (int i = 1; i <= num; i++) {
    cout << over3 << "Enter score " << i << ": " << endl;
    cout << over3 << "Enter a value from 0 to 100: ";
    cin >> score;
    while (score < 0 || score > 100) {
      cout << over3 << score
           << " is not between 0 and 100! Renter the score: " << i << ": ";
      cin >> score;
    }
    total += score;
  }
}

其余的会一样...... 否则在这种情况下我不会使用3个参数。 e.g,

int validateNumber(int num) {
  int total=0,score;
  while (num < 1 || num > 4) {
    cout << over3 << num << " is not between 1 and 4! Try again: ";
    cin >> num;
  }
  system("CLS");
  for (int i = 1; i <= num; i++) {
    cout << over3 << "Enter score " << i << ": " << endl;
    cout << over3 << "Enter a value from 0 to 100: ";
    cin >> score;
    while (score < 0 || score > 100) {
      cout << over3 << score
           << " is not between 0 and 100! Renter the score: " << i << ": ";
      cin >> score;
    }
    total += score;
  }
  return total;
}

和电话:

int num, total;
...
total=validateNumber(num);

希望它有所帮助...

答案 1 :(得分:0)

您是否假设第5行中的函数调用validateNumber(num,score,total);会计算总数?您应该从main函数调用函数,并将返回值赋给变量(例如total)。