如何在C++ max()函数中传入多个变量,将负值统一设置为0
原子序数转电子排布代码问题修复
问题说明
代码在处理小于轨道填充起始阈值的原子序数时,减法运算会得到负数结果,比如输入原子序数57时,计算d5的逻辑为d5 = n-70,得到的结果为-13,就会出现不符合预期的负值输出。
最优解决方案
不需要新增19条判断语句,也不需要一次性给max传19个参数,直接对每个变量单独调用双参数的std::max函数即可,std::max(a, 0)会自动把小于0的a替换为0,大于等于0的a保留原值,完全匹配需求。
具体修改步骤:
- 在头文件部分新增引入
<algorithm>,std::max函数定义在该头文件中 - 在所有轨道变量赋值完成、特殊轨道半满/全满规则调整代码之后,为每个变量增加一次和0取最大值的操作
修改后的完整代码:
#include<iostream> #include<algorithm> // 新增引入max函数所需头文件 using namespace std; int main() { int n, s1, s2, p2, s3, p3, s4, d3, p4, s5, d4, p5, s6, f4, d5, p6, s7, f5, d6, p7; cout << "Atomic number: "; cin >> n; if(n<=2){ s1 = n; } else if(n>=2){ s1 = 2; } if(n<=4){ s2 = n-2; } else if(n>=4){ s2 = 2; } if(n<=10){ p2 = n-4; } else if(n>=10){ p2 = 6; } if(n<=12){ s3 = n-10; } else if(n>=12){ s3 = 2; } if(n<=18){ p3 = n-12; } else if(n>=18){ p3 = 6; } if(n<=20){ s4 = n-18; } else if(n>=20){ s4 = 2; } if(n<=30){ d3 = n-20; } else if(n>=30){ d3 = 10; } if(n<=36){ p4 = n-30; } else if(n>=36){ p4 = 6; } if(n<=38){ s5 = n-36; } else if(n>=38){ s5 = 2; } if(n<=48){ d4 = n-38; } else if(n>=48){ d4 = 10; } if(n<=54){ p5 = n-48; } else if(n>=54){ p5 = 6; } if(n<=56){ s6 = n-54; } else if(n>=56){ s6 = 2; } if(n<=70){ f4 = n-56; } else if(n>=70){ f4 = 14; } if(n<=80){ d5 = n-70; } else if(n>=80){ d5 = 10; } if(n<=86){ p6 = n-80; } else if(n>=86){ p6 = 6; } if(n<=88){ s7 = n-86; } else if(n>=88){ s7 = 2; } if(n<=102){ f5 = n-88; } else if(n>=102){ f5 = 14; } if(n<=112){ d6 = n-102; } else if(n>=112){ d6 = 10; } if(n<=118){ p7 = n-112; } else if(n>=118){ p7 = 6; } // 特殊轨道调整规则 if(d3==4 && s4==2){ d3++; s4--; } if(d3==9 && s4==2){ d3++; s4--; } if(d4==9 && s5==2){ d4++; s5--; } if(d4==4 && s5==2){ d4++; s5--; } // 新增:所有负值统一转为0 s1 = max(s1, 0); s2 = max(s2, 0); p2 = max(p2, 0); s3 = max(s3, 0); p3 = max(p3, 0); s4 = max(s4, 0); d3 = max(d3, 0); p4 = max(p4, 0); s5 = max(s5, 0); d4 = max(d4, 0); p5 = max(p5, 0); s6 = max(s6, 0); f4 = max(f4, 0); d5 = max(d5, 0); p6 = max(p6, 0); s7 = max(s7, 0); f5 = max(f5, 0); d6 = max(d6, 0); p7 = max(p7, 0); // 输出 cout << "s1: " << s1; cout << "\ns2: " << s2; cout << "\np2: " << p2; cout << "\ns3: " << s3; cout << "\np3: " << p3; cout << "\ns4: " << s4; cout << "\nd3: " << d3; cout << "\np4: " << p4; cout << "\ns5: " << s5; cout << "\nd4: " << d4; cout << "\np5: " << p5; cout << "\ns6: " << s6; cout << "\nF4: " << f4; cout << "\nd5: " << d5; cout << "\np6: " << p6; cout << "\ns7: " << s7; cout << "\nf5: " << f5; cout << "\nd6: " << d6; cout << "\np7: " << p7; return 0; }
关于多参数max的补充说明
如果你确实需要一次性对多个变量取最大值,C++11及以上版本可以用初始化列表的写法:max({a, b, c, d}),但你的场景是要给每个变量单独置0,不需要这种写法,单独调用双参数max是最高效、可读性最好的方案。
内容的提问来源于stack exchange,提问作者Abdullah Mert Özdemir
相关产品推荐
相关产品推荐

