现场编码题目2:
某集团有三个单位A、B、C,三个单位总人数有900人,A单位人数的比B单位人数多320人,C单位人数平方比A单位人数少200人,请问A、B、C三个单位人数各自多少?
编码算法规定:通过三层循环穷举方法,同时,注意循环算法的优化。正确答案:A=600,B=280,C=20,请用编码求解。
声明:下方的参考代码并不是最优解法。
参考代码Python版:
bFinished=False for A in range(1,901): for B in range(1,901): for C in range(1,901): if(A+B+C==900 and A-B==320 and A-C*C==200): print(A,B,C) bFinished=True break if(bFinished==True): break if(bFinished==True): break print("over")
参考代码C#版:
using System; namespace Case2 { class Program { static void Main(string[] args) { bool bFinished = false; for (int A = 1; A <= 900; A++) { for (int B = 1; B <= 900; B++) { for (int C = 1; C <= 900; C++) { if (A + B + C == 900 && A - B == 320 && A - C * C == 200) { Console.WriteLine("A:{0},B:{1},C:{2}", A, B, C); bFinished = true; break; } } if (bFinished == true) break; } if (bFinished == true) break; } Console.WriteLine("over"); } } }
参考代码 C++:
#include <iostream> using namespace std; int main() { bool bFinished = false; for (int A = 1; A <= 900; A++) { for (int B = 1; B <= 900; B++) { for (int C = 1; C <= 900; C++) { if (A + B + C == 900 && A - B == 320 && A - C * C == 200) { cout << "A:"<<A << " B:"<<B << " C:"<<C<<endl; bFinished = true; break; } } if (bFinished == true) { break; } } if (bFinished == true) { break; } } }