Rust 写过了的,还有个 C++ 版本。
最终代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include <iostream> #include <cmath> using namespace std; void nya(double a, double b, double c) { long double delta = (b * b) - (4.0 * a * c); if (delta > 0.0) { long double x1 = ((-b) + sqrt(delta)) / (2.0 * a); long double x2 = ((-b) - sqrt(delta)) / (2.0 * a); cout << "Two results: x1 = " << x1 << "; x2 = " << x2 << "." << endl; } if (delta == 0.0) { long double x = (-b) / (2.0 * a); cout << "One result: x = " << x << "." << endl; } if (delta < 0.0) { cout << "No result." << endl; } } int main() { long double a, b, c; char r; while(true) { cout << "Please input a = "; cin >> a; cout << "Please input b = "; cin >> b; cout << "Please input c = "; cin >> c;
nya(a, b, c); cout << "Continue?[Y/n]" << endl; cin >> r; if (r == 'n') { break; } } return 0; }
|
细节
创建文件夹(
1 2 3 4
| $ cd ~ $ mkdir cpp-quadratic-equation $ cd cpp-quadratic-equation $ touch a.cpp
|
主函数部分
先创建一个main
函数
1 2 3 4
| int main() { return 0; }
|
声明 a
b
c
变量
1 2 3 4
| int main() { long double a, b, c; return 0; }
|
我想创建一个可重复的函数(与Rust
版本的函数不同)。
如果用户希望重复计算过程,只需输入任何内容并按回车键,输入n
退出。
1 2 3 4 5 6 7 8 9 10 11 12 13
| int main() { long double a, b, c; char r; while(true) { cout << "Continue?[Y/n]" << endl; cin >> r; if (r == 'n') { break; } } return 0; }
|
获取输入呐~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| int main() { long double a, b, c; char r; while(true) { cout << "Please input a = "; cin >> a; cout << "Please input b = "; cin >> b; cout << "Please input c = "; cin >> c;
cout << "Continue?[Y/n]" << endl; cin >> r; if (r == 'n') { break; } } return 0; }
|
主运算函数部分
这个就不需要返回值了
1 2 3
| void nya(double a, double b, double c) {
}
|
声明delta
变量
1 2 3
| void nya(double a, double b, double c) { long double delta = (b * b) - (4.0 * a * c); }
|
逻辑判断部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void nya(double a, double b, double c) { long double delta = (b * b) - (4.0 * a * c); if (delta > 0.0) { long double x1 = ((-b) + sqrt(delta)) / (2.0 * a); long double x2 = ((-b) - sqrt(delta)) / (2.0 * a); cout << "Two results: x1 = " << x1 << "; x2 = " << x2 << "." << endl; } if (delta == 0.0) { long double x = (-b) / (2.0 * a); cout << "One result: x = " << x << "." << endl; } if (delta < 0.0) { cout << "No result." << endl; } }
|
主运算函数完成了
合体!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| void nya(double a, double b, double c) { }
int main() { while(true) { nya(a, b, c); cout << "Continue?[Y/n]" << endl; cin >> r; if (r == 'n') { break; } } return 0; }
|
nya
函数必须写在主函数前面,这是 C++ 标准的规定,要不不能调用(
调试
不同操作系统有不同的规矩,这里用 macOS + Clang 示例
1 2
| $ clang++ a.cpp $ ./a.out
|