0

这是我发现的一个问题,我真的不知道答案。假设我们有以下代码:

int grade = 100;
string finalgrade = (grade > 90) ? "High Pass"
                                 : (grade > 75) ? "Pass"
                                                : (grade >= 60) ? "low pass" : "fail";

如果条件运算符保持关联,将如何评估它?

4

2 回答 2

2

如果?:是左联想,那将意味着:

a ? b : c ? d : e

相当于:

(a ? b : c) ? d : e

代替:

a ? b : (c ? d : e)

将此应用于您的示例,您将获得:

string finalgrade =   (  (  (grade > 90)
                          ? "High Pass"
                          : (grade > 75))
                       ? "Pass"
                       : (grade >= 60))
                    ? "low pass"
                    : "fail";

其中——假设编译器没有抱怨不匹配的类型——forgrade = 100将导致:

string finalgrade =   (  (  true
                          ? "High Pass"
                          : (grade > 75))
                       ? "Pass"
                       : (grade >= 60))
                    ? "low pass"
                    : "fail";

string finalgrade =   (  "High Pass"
                       ? "Pass"
                       : (grade >= 60))
                    ? "low pass"
                    : "fail";

string finalgrade =   "Pass"
                    ? "low pass"
                    : "fail";

string finalgrade = "low pass";
于 2013-07-19T10:08:44.080 回答
0

在你的例子中:finalgrade =“高通”

计算是从右到左完成的

于 2013-07-19T10:05:55.967 回答