简体   繁体   English

从并行数组返回值,并在以后的函数中使用这些值

[英]Return values from parallel arrays and use those values in later functions

I am at a loss. 我很茫然。 I have tried several things and have 90% of the program working. 我已经尝试了几件事,并且有90%的程序正在工作。 In fact, it compiles and runs fine. 实际上,它可以编译并运行良好。 My output is very bizarre characters where the letter grade is supposed to be. 我的输出是字母等级应该是的非常奇怪的字符。

Our textbook does not offer examples with things like this and it is very difficult to search for. 我们的教科书没有提供类似此类示例,因此很难搜索。 I need to return a letter grade in one function and use it in a table later on in another function. 我需要在一个函数中返回字母等级,然后在表中的另一个函数中使用它。 How do you do this? 你怎么做到这一点?

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

// function prototypes
void getData(string [], string [], int []);
char calculateGrade(char []);
void printResult(string [], string [], int [], char [], int);

int main()
{
    // define 4 parallel arrays
    const int NO_OF_STUDENTS = 5;
    string studentFNames[NO_OF_STUDENTS];
    string studentLNames[NO_OF_STUDENTS];
    int testScores[NO_OF_STUDENTS];
    char letterGrades[NO_OF_STUDENTS];

    // call getData() to populate three of the four parallel arrays
    getData(studentFNames, studentLNames, testScores);

    // call calculateGrade() to provide values for the fourth parallel array
    calculateGrade(letterGrades);

    // call printResult() to display report form the parralel arrays
    printResult(studentFNames, studentLNames, testScores, letterGrades, NO_OF_STUDENTS);

    return 0;
}

// function definition getData()
void getData(string fName[], string lName[], int scores[])
{
    // the follow arrays are used for test data (do not modify)
    string fNameTest[5] = {"Humpty", "Jack", "Mary", "Jack", "King"};
    string lNameTest[5] = {"Dumpty", "Horner", "Lamb", "Sprat", "Cole"};
    int scoresTest[5] = {59, 88, 100, 75, 60};


    // use a suitable loop to populate the appropriate "empty" arrays
    // with values from the three initialized test arrays
    for(int index = 0; index < 5; index++)
    {
        fName[index] = fNameTest[index];
        lName[index] = lNameTest[index];
        scores[index] = scoresTest[index];
    }
}

// function definition for calculateGrade()
char calculateGrade(char letter[])
{
    int score;
    char gradeLetter[5] = {'A', 'B', 'C', 'D', 'F'};

    //for(int i = 0; i < 5; i++)
    //{

        if(score > 89)
        {
            return gradeLetter[0];
        }
        if(score > 79)
        {
            return gradeLetter[1];
        }
        if(score > 69)
        {
            return gradeLetter[2];
        }
        if(score > 59)
        {
            return gradeLetter[3];
        }


        return gradeLetter[4];

    //}

}

// function definition for printResults()
void printResult(string lName[], string fName[], int score[], char letter[], int size)
{
    cout << setw(15) << left << "Student Name" << setw(9) << right << "Test Score" << " " << setw(5) << "Grade" << endl << endl;
    for(int index = 0; index < size; index++)
    {
        cout << setw(15) << left << (lName[index] + ", " + fName[index]);
        cout << setw(9) << right << score[index] << " " << setw(5) << letter[index] << endl;
    }
}

Here is the program. 这是程序。 Keep in mind that I have to use only the three functions and I cannot change any of the constants or local variables. 请记住,我只需要使用这三个函数,就不能更改任何常量或局部变量。 I suspect later we are going to modify this program later to read from a file but that is not the issue as of now. 我怀疑稍后我们将稍后修改该程序以从文件中读取,但是到目前为止这还不是问题。

I have tried a for loop with the if/else if/else statements and that gives spades, diamonds, and w's. 我已经尝试过使用if / else if / else语句进行for循环,并且得到黑桃,菱形和w。 I have tried using arrays for gradeLetter and testScores and I still get gibberish in return. 我已经尝试过将数组用于gradeLetter和testScores,但我仍然会得到一些胡言乱语。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Sorry if something similar has been done. 抱歉,是否已完成类似操作。 It's a nightmare searching for something like this. 寻找这样的东西真是一场噩梦。

Try the following method instead of yours: 请尝试以下方法代替您的方法:

// function definition for calculateGrade()
  void calculateGrade(const int NO_OF_STUDENTS, int *testScores, char *letter)
  {
     for(int i = 0; i < NO_OF_STUDENTS; i++)
     {

       if(testScores[i] > 89)
       {
           letter[i] = 'A';
       }
       else if(score > 79)
       {
           letter[i] = 'B';
       }
       else if(score > 69)
       {
           letter[i] = 'C';
       }
       else if(score > 59)
       {
           letter[i] = 'D';
       }
       else // As you are a beginner, try to always cover all the possibilities in an if chain, you'll thank me later
           printf("Please give a score greater than 59 for student number %d", i);


  }

and call like this: 并这样调用:

calculateGrade(NO_OF_STUDENTS, testScores, letterGrades);

As it is homework I'll let you discover the meaning of the asterisk and why I don't return a value. 因为这是家庭作业,所以我将让您发现星号的含义以及为什么我不返回任何值。

And a final advice, maybe for a later moment when you have a better grasp of the language, try to group the fields in a class or struct (almost the same in C++, check this What are the differences between struct and class in C++? for the diff) and instead of array of first, last names and scores you'll end up with something like: 最后一条建议,也许是稍后您对语言有更好的了解时,请尝试将字段分组为类或struct(在C ++中几乎相同,请检查一下)。C ++ 中的struct和class有什么区别?的差异),而不是名字,姓氏和分数的数组,您将得到类似以下内容的结果:

struct Student  
{
   string fName;
   string lName;
   int testScore;
}

Student students[NO_OF_STUDENTS];

This code is not very well written, but, as a quick fix, you might just initialize your char LetterGrades[] , just as you have initialized 3 other arrays. 这段代码写得不太好,但是,作为快速解决方案,您可以只初始化char LetterGrades[] ,就像初始化了其他3个数组一样。 So, you could do> 因此,您可以>

    char calculateGrade(char letter[])
{
    int score;
    char gradeLetter[5] = {'A', 'B', 'C', 'D', 'F'};

    for(int i=0; i<5; i++) {
        letter[i] = gradeLetter[i];
    }

        if(score > 89)
        {
            return gradeLetter[0];
        }
        if(score > 79)
        {
            return gradeLetter[1];
        }
        if(score > 69)
        {
            return gradeLetter[2];
        }
        if(score > 59)
        {
            return gradeLetter[3];
        }

        return gradeLetter[4];

    //}

}

Output is then OK, it prints out 'A', 'B', 'C' etc. One more thing, your printResult function is poorly written. 然后输出就可以了,它会打印出“ A”,“ B”,“ C”等。 printResult ,您的printResult函数写得不好。 It doesn't do anything but just list out all of the arrays (test and you'll see that score 59 gets an 'A' and score 100 gets 'C'). 它什么也没做,只是列出所有数组(测试,您会看到59分获得“ A”,而100分获得“ C”)。 You have to make code so that scores and grades are corresponding with people who earned them. 您必须编写代码,以便分数和等级与获得这些分数的人相对应。

calculateGrade has two problems: calculateGrade有两个问题:

  1. You can see from your compiler warnings. 您可以从编译器警告中看到。 score is uninitialized score未初始化
  2. It doesn't assign anything to letter[] 它不给letter[]分配任何内容letter[]

The concept of your program is that each index represents a student. 该程序的概念是每个索引代表一个学生。 So what you want is to take in the score of an index (student) and assign it to that index's (student's) letter . 因此,您想要获取索引(学生)的分数,并将其分配给该索引(学生)的letter

To do that we need to take in a score and a letter. 为此,我们需要输入分数和字母。 So your definition should look like: void calculateGrade(int[], char[]); 因此,您的定义应如下所示: void calculateGrade(int[], char[]); . Internally rather than returning the grade letter you'd assign it to the char[] . 在内部而不是返回将其分配给char[]的等级字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM