Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        5年前关闭。
                                                                                            
                
        
我发现这个问题我真的不知道答案。假设我们有以下代码:

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


如果将条件运算符置于关联状态,将如何评估?

最佳答案

如果?:是左关联的,则意味着:

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";


假设编译器没有抱怨类型不匹配的情况,对于grade = 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";

关于c++ - C++如果条件运算符被左关联怎么办,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17743354/

10-17 00:31