【问题标题】:User sized based array function to print out something if there are values higher than 90如果值高于 90,则基于用户大小的数组函数打印出一些东西
【发布时间】:2011-12-15 07:23:33
【问题描述】:

我正在设置一个基于用户大小的数组来输入一些分数并打印出最高和最低值以及平均值。我还想使用布尔函数来打印是否有任何 A 级(分数高于 90)但是我不太确定如何编码。我在下面尝试了 getAScores 函数,但它不起作用。

#include <iostream> 
using namespace std; 
#include <iomanip>  
#include <cstdlib>

int compare(const void* pa, const void* pb) 
{ 
  const int& a = *static_cast<const int*>(pa); 
  const int& b = *static_cast<const int*>(pb); 
  if (a < b) return -1; // negative if a<b 
  if (a > b) return 1; // positive if a>b 
  return 0; // 0 for tie 
} // compare 

double getAverage(int* score, int n) 
{ 
  int sum = 0; 
  int i = 0; 
  for (i = 0; i < n; i++) 
    sum += score[i]; 
  double average = double(sum) / n; 
  return average; 
} // getAverage 
//Boolen Function to see if there are A grades present 
bool getAGrades(int* score) 
{ 
  int i = 0;
  if (score[i] >= 90){
  return true;
  cout << "there is at least one A"<<endl;
  }else {
   return false;
  cout<<" No A Grades "<<endl;
}
}
int main() 
{  
  int size;
  cout << "How many scores? ";
  cin >> size;
  cin.ignore(1000, 10);
  int* score = new int[size];  

  int i; // loop counter 
  for (i = 0; i < size; i++) 
  { 
    cout<< "Enter a number: ";
    cin >> score[i]; 
    cin.ignore(1000, 10); 
  } // for 

qsort(score, size, sizeof(int), compare); 
for (int i = 0; i < size; i++) {
    cout << score[i] << ' ';
  }
  cout <<endl;
  cout << "Lowest score  = " << score[0] << endl;
  cout << "Highest score = " << score[size-1] << endl;
  cout << fixed << setprecision(1);
  cout << "Average = " << getAverage(score, size) << endl; 
  //this is where i want it to print if there are a grades or not
  getAGrades(score);


  return 0; 
} // main

【问题讨论】:

  • 请详细说明你想要从这个函数中得到什么:bool getAGrades(int* score)。目前它只查看一个索引(0),这没有意义。
  • 另外,尽量不要使用cin.ignore()。我假设这是一项基本作业,您不需要执行复杂的输入过滤。
  • 如果这是作业,请添加homework-tag。

标签: c++ function boolean


【解决方案1】:

您需要使用循环来查看所有索引(就像您在 getAverage 中所做的那样)。这要求getAGrades 知道数组的大小。

另外,请注意在 return 之后放置 cout 是没有意义的 - 它永远不会被执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多