我不明白如何在 Visual Studio 中修复此功能
continue
I'm getting the following error in Visual Studio that I don't understand:
main.cpp(21): error C2440: '=': cannot convert from 'void' to 'char'
main.cpp(21): note: Expressions of type void cannot be converted to other types
This is my code:
void getLetterGrade(double totalAvg, char& letter_Grade)
{
if (totalAvg >= 90) {
letter_Grade = 'A';
}
else if (totalAvg < 90 && totalAvg >= 80) {
letter_Grade = 'B';
}
else if (totalAvg < 80 && totalAvg >= 70) {
letter_Grade = 'C';
}
else if (totalAvg < 70 && totalAvg >= 60) {
letter_Grade = 'F';
}
}
int main()
{
double totalGrade = 74;
char letterGRADE;
letterGRADE = getLetterGrade(totalGrade, letterGRADE);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的函数
getLetterGrade
返回void
,这意味着“什么都没有”。因此,在赋值的右侧使用它是非法的。这里
会导致错误,因为它尝试使用函数的返回值,但没有。
但是,由于您通过引用传递第二个参数(通过说“char & letter_Grade”),您已经获得了所需的字母。只需将您的代码更改为
即可。当被调用函数返回时,变量
letterGRADE
的值已经被更新。作为替代方案,您可以更改函数以返回字母:
现在您可以像这样调用它,使用返回值:
Your function
getLetterGrade
returnsvoid
, that means "nothing". Therefore it is illegal to use it on the right hand side of an assignment.This here
will result in an error, because it tries to use the return value of the function, but there is none.
But, since you pass the second parameter by reference (by saying "char & letter_Grade") you already get the required letter back. Just change your code to
and you should be fine. The value of the variable
letterGRADE
will already have been updated when the called function returns.As an alternative, you could change the function to return the letter instead:
Now you would call it like so, using a return value: