我终于解决了并通过 strcmp 链接数组以发挥作用并比较数组值。感谢你的帮助!!希望你们能引用我的问题和帖子中列出的答案。
感谢所有发表评论并提出相应建议的人。欣赏它。
我的解决方案是通过使用 2D 数组 - char 而不是字符串 + 使用 strcmp at 函数来比较值集以实现 Lab7 的目标来解决它。
最好的,
MM
// Marcus Moo Lab 7.cpp
// Full Time Student
// No plagarism
#include <iostream>
#include <string>
using namespace std;
// Global Declarations
const float pointLaw[11] = { 5.0,5.0,4.5,4.0,3.5,3.0,2.5,2.0,1.5,1.0,0.0 };
const char gradeLaw[11][3] = { "A+","A","A-","B+","B","B-","C+","C","D+","D","F" };
// Convert Grade to Point
float gradeToPoint(const char grade[]);
int main()
{
// Header
cout << "\tWelcome to University Of Wollongong" << endl;
cout << "Grade Point Consultation System" << endl;
cout << endl;
// Defining moments
char grade[3];
float outcome;
char intent;
int count;
// Purpose of consultation system
do
{
cout << "Enter your grade: ";
cin >> grade;
outcome = gradeToPoint(grade);
if (outcome == -1) {
cout << "Invalid Grade" << endl;
}
else {
cout << "Your grade point is " << outcome << endl;
}
cout << "Continue?: ";
cin >> intent;
cout << endl;
} while ((intent == 'y') || (intent == 'Y'));
// The end
cout << "All the best" << endl;
}
float gradeToPoint(const char grade[])
{
int count;
float points = -1;
for (count = 0; count < 12; count++)
{
if (strcmp(gradeLaw[count], grade) == 0) {
points = pointLaw[count];
cout << gradeLaw[count] << " = " << grade << endl;
}
}
return points;
}
最佳答案
更简单的方法是使用结构对记录建模(想想表中的一行):
struct Name_Grade
{
std::string grade;
double point;
};
这会将成绩与分值配对。
现在声明每个数组:
static const grade_table[] =
{
{"A+", 5.0}, {"A", 5.0}, {"A-", 4.5}, //...
};
size_t rows_in_table =
sizeof(grade_table) / sizeof(grade_table[0]);
你的函数变成:
double gradeToPoint(const std::string& grade)
{
double point = 0.0;
for (size_t i = 0; i < rows_in_table; ++i)
{
if (grade == grade_table[i].grade)
{
point = grade_table[i].point;
break;
}
}
return point;
}
使用并行数组:
double grade_to_point(const std::string& grade)
{
static const std::string grade_texts[]=
{"A+", "A", "A-",
"B+", "B", "B-",
"C+", "C", "C-",
"D+", "D",
"F"};
static const double point[] =
{5.0,5.0,4.5,
3.5,3.0,2.5,
2.5,2.0,1.5,
1.0,0.5,
0.0};
static const size_t grade_quantity =
sizeof(point) / sizeof(point[0]);
double grade_value = 0.0;
for (size_t i = 0; i < grade_quantity; ++i)
{
if (grade == grade_texts[i])
{
grade_value = point[i];
break;
}
}
return grade_value;
}
并行数组的一个问题是数组的大小可能不同,或者不同步。因此,更安全、更可靠的方法是将成绩文本与分值保持一致(struct
方法)。
关于c++ - 如何通过函数 C++ 链接数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42284030/