算法竞赛入门经典chapter4:本章小结

编写一个 函数solve,给定浮点数a, b, c, d, e, f,求解方程组af + by = c, dx + ey = f;

任务1:使用assert宏,让解不唯一时异常退出。

任务1
 1 #include<iostream>
 2 #include<cassert>
 3 using namespace std;
 4 
 5 double x, y;
 6 
 7 void solve(double a, double b, double c, double d, double e, double f)
 8 {
 9     assert(b*d!=a*e);
10     y = (c*d-a*f)/(b*d-a*e);
11     x = (c-b*y)/a;
12 }
13 
14 int main()
15 {
16     double a, b, c, d, e, f;
17     cout << "Please input some values!" << endl;
18     while(cin >> a >> b >> c >> d >> e >> f)
19     {
20         solve(a, b, c, d, e, f);
21         cout << x << "  " << y << endl;
22     }
23     return 0;
24 }

任务2:

解不唯一时仍然正常返回,但调用者有办法知道解的数量(无解、唯一解、无穷多组解)。

任务2
 1 #include<iostream>
 2 #include<cassert>
 3 using namespace std;
 4 
 5 double x, y;
 6 int solve(double a, double b, double c, double d, double e, double f)
 7 {
 8     if(b*d==a*e)
 9         return 0;
10     y = (c*d-a*f)/(b*d-a*e);
11     x = (c-b*y)/a;
12     return 1;
13 }
14 int main()
15 {
16     double a, b, c, d, e, f;
17     cout << "Please input some values!" << endl;
18     while(cin >> a >> b >> c >> d >> e >> f)
19     {
20         if(!solve(a, b, c, d, e, f))
21             cout << "无穷多解!!" << endl;
22         else
23         cout << x << "  " << y << endl;
24     }
25     return 0;
26 }

思考:函数的参数都有哪些?格式什么类型?

size命令给出的是运行时的BBS段大小,但在可执行文件中,只保存每个变量所需的空间,并不存储他们的映像;相反,已初始化的全局变量必须把映像存在可执行文件中。

实验1:声明全局变量int a[1000000],不要声明其他变量,编译后查看可执行文件的大小,并用size命令查看各个段的大小。

实验1
1 C:\Users\桑海\Desktop>size a.exe
2    text    data     bss     dec     hex filename
3    3028     772 4000120 4003920  3d1850 a.exe

实验2:声明全局变量int a[1000000] = {1},不要声明其他变量,编译后查看可执行文件的大小,并用size命令查看各个段的大小。如果把初值改成{0}呢?

实验2
1    C:\Users\桑海\Desktop>size a.exe
2    text    data     bss     dec     hex filename
3    3028 4000772      96 4003896  3d1838 a.exe
4 改为0
5    C:\Users\桑海\Desktop>size a.exe
6    text    data     bss     dec     hex filename
7    3028     772 4000120 4003920  3d1850 a.exe

实验3:用-g(调试信息)和-O2(二级优化)编译任务1和任务2的代码。可执行文件的大小如何变化?各段的大小如何变化?

实验3
 1 C:\Users\桑海\Desktop>gcc assert.cpp -g -o2
 2 
 3 C:\Users\桑海\Desktop>size 2.exe
 4    text    data     bss     dec     hex filename
 5    3556     812     112    4480    1180 2.exe
 6 
 7 C:\Users\桑海\Desktop>gcc assert.cpp -g -o2
 8 
 9 C:\Users\桑海\Desktop>size  2.exe
10    text    data     bss     dec     hex filename
11    3540     812     112    4464    1170 2.exe
原文地址:https://www.cnblogs.com/sanghai/p/2879178.html