无聊发个求一元二次方程的代码
这是vc++/CLR代码,用vs的同学该知道怎么创建项目和编译,编译不了也没关系,代码干什么和怎么干的,一目了然,用自己的方法,也能照着做出同样的事。要移植为非托管代码的,自己写出类似的替代函数就可以了,因为需要划分的功能是一样的。程序代码:
#include "stdafx.h" using namespace System; Double GetCoefficient(String^ tips); // 交互获取方程系数 Int32 main(array<String^>^ args) { Console::Title = L"一元二次方程的解"; Console::Clear(); Double coefficient_A, coefficient_B, coefficient_C; while ((coefficient_A = GetCoefficient(L"\n请输入二次项系数(输入零结束程序) A: ")) != 0) { coefficient_B = GetCoefficient(L"请输入一次项系数 B: "); coefficient_C = GetCoefficient(L"请输入常数项系数 C: "); Console::Clear(); Console::WriteLine(L"您需要求解的方程是:{0} * x^2 + {1} * x + {2} = 0", coefficient_A, coefficient_B, coefficient_C); Double delta = coefficient_B * coefficient_B - 4 * coefficient_A * coefficient_C; if (delta == 0) { Double theUnknown = - coefficient_B / (2 * coefficient_A); Console::WriteLine(L"方程的根为: {0:F4}", theUnknown); } if (delta > 0) { Double theUnknown1, theUnknown2; theUnknown1 = (- coefficient_B + Math::Sqrt(delta)) / (2 * coefficient_A); theUnknown2 = (- coefficient_B - Math::Sqrt(delta)) / (2 * coefficient_A); Console::WriteLine(L"方程的根为: {0:F4}, {1:F4}", theUnknown1, theUnknown2); } if (delta < 0) { Console::WriteLine(L"方程没有实数根"); } } return 0; } // 交互获取方程系数 Double GetCoefficient(String^ tips) { Double returnValue; do { Console::Write(tips); } while (!Double::TryParse(Console::ReadLine(), returnValue)); return returnValue; }
[ 本帖最后由 TonyDeng 于 2014-12-12 23:51 编辑 ]