string definition problem
int main()
{
int score;
string scoreLetter;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
v开发者_JAVA百科oid letterGrade (int score);
void gradeFinal (int score);
cout<<"The letter grade is "<< scoreLetter<<".";
}
void letterGrade (int score)
{
if (score >= 90) {
string scoreLetter = 'A'
} else if (score >= 80) {
scoreLetter = 'B'
} else if (score >= 70)
-When compiling, I am getting an error for the line scoreLetter = 'A', etc. What is wrong with this? Error states 'scoreLetter' undefined. Do I need to define scoreLetter in the function not the main?
Single quotes in C/C++ are used to define a character, not a String. Use double quotes instead. string scoreLetter = "A"
. Also you need to include the header if std::string
is what you are trying to use: #include <string>
and using std::string
.
You'll want to return whatever value your function determines scoreLetter
should be, and in main
have a line like scoreLetter = letterGrade(score);
. You can't set local variables from another function, unless the caller passed them to you by reference, which isn't happening here (and, in most cases, shouldn't be abused like that).
Aside from that, it looks like you're mixing up declarations and invocations. void letterGrade (int score);
doesn't actually call letterGrade
; it just says that there is a letterGrade
function that takes an int, which we'll call "score". (The score
there is just a name that's part of the prototype; it has no connection to your score
variable.) So you'll likely find that if you managed to get your code to compile, it'd do something quite different than you're expecting it to do.
To call a function, you'd do something like letterGrade(score);
, or if you followed my first suggestion, scoreLetter = letterGrade(score);
.
string letterGrade (int score);
// void gradeFinal (int score); // not used in this snippet
int main()
{
int score;
string scoreLetter;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
scoreLetter = letterGrade(score);
cout<<"The letter grade is "<< scoreLetter<<".";
}
string letterGrade (int score)
{
string grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70)
...
return grade;
}
Your code is cut off there but I think from what is available you are not calling the functions properly.
You should also try to be more specific about what language you are talking about, i.e. C in this case I believe.
A correct call to the functions would be:
letterGrade(score);
And yes, you need to define the string variable at global scope, so just move it out of main and above it.
string scoreLetter;
int main()
{
int score;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
letterGrade (score);
gradeFinal (score);
cout<<"The letter grade is "<< scoreLetter<<".";
}
void letterGrade (int score)
{
if (score >= 90) {
scoreLetter = "A"
} else if (score >= 80) {
scoreLetter = "B"
} else if (score >= 70)
精彩评论