标签:
第四章小问题集锦
以上是我这一章课后题思考的流程,有错误和不严谨地方请直接指出!
1、解方程组
任务一:使用assert宏,解不唯一时异常退出
#include <stdio.h>
//x=(ce-bf)/(ae-bd), y=(cd-af)/(bd-ae)
int solve(double a, double b, double c, double d, double e, double f){
assert(a*e != b*d);
...
}
int main(){
double a,b,c,d,e,f;//
scanf("%lf%lf%lf%lf%lf%lf", &a,&b,&c,&d,&e,&f);
solve(a,b,c,d,e,f);
return 0;
}
任务二:
#include <stdio.h>
//x=(ce-bf)/(ae-bd), y=(cd-af)/(bd-ae)
int solve(double a, double b, double c, double d, double e, double f){
//assert(a*e != b*d);
if(a*e == b*d){
if(c*d != a*f) return 0;//无解
return 2;//无数解
}else return 1;//唯一
}
int main(){
double a,b,c,d,e,f;//
scanf("%lf%lf%lf%lf%lf%lf", &a,&b,&c,&d,&e,&f);
if(solve(a,b,c,d,e,f) == 0) printf("无解\n");
else if(solve(a,b,c,d,e,f) == 1) printf("唯一解\n");
else printf("无数解\n");
return 0;
}
任务三:
函数的参数都是double,代表a,b,c,d,e,f 六个数字
2、编写程序,包含三个函数 f g h 均无参数,返回均为int型
任务一+任务二:定义全局变量即可(在f g h中++与--)
3、编程探索
问题一:局部变量和全局可以重名,不影响程序效果,但是会影响人的感官判断。
问题二:有效,因为地址空间是真枪实弹的,一次改变就变了。
以下是测试过程:
gcc会有warning,执行结果没问题。
C:\Users\tfans\Desktop>gcc test.c -g -O2
test.c: In function ‘f‘:
test.c:6:5: warning: return makes integer from pointer without a cast [enabled b
y default]
test.c:6:5: warning: function returns address of local variable [enabled by defa
ult]
测试程序:
#include <stdio.h>
int f(){
int n = 4;
//int*p = &n;
//printf("%d\n", );
return &n;
}
int main(){
int a = 10;
//f();
//通过如下形式调用f里的n的地址,将n取出打印
printf("%d\n", *((int *)f()));
return 0;
}
4、3个size实验
不用-g -O2编译:
实验一:
#include <stdio.h>
int a[1000000];
int main(){
return 0;
}
C:\Users\tfans\Desktop>gcc test.c
C:\Users\tfans\Desktop>size a.exe
text data bss dec hex filename
4260 940 4000112 4005312 3d1dc0 a.exe
实验二:
#include <stdio.h>
int a[1000000]={1};
int main(){
return 0;
}
C:\Users\tfans\Desktop>gcc test.c
C:\Users\tfans\Desktop>size a.exe
text data bss dec hex filename
4260 4000940 96 4005296 3d1db0 a.exe
若把{1}改成{0}
#include <stdio.h>
int a[1000000]={0};
int main(){
return 0;
}
C:\Users\tfans\Desktop>gcc test.c
C:\Users\tfans\Desktop>size a.exe
text data bss dec hex filename
4260 940 4000120 4005320 3d1dc8 a.exe
用-g -O2编译:
实验一:
C:\Users\tfans\Desktop>gcc test.c -g -O2
C:\Users\tfans\Desktop>size a.exe
text data bss dec hex filename
4260 940 4000112 4005312 3d1dc0 a.exe
无变化!
实验二:
C:\Users\tfans\Desktop>gcc test.c -g -O2
C:\Users\tfans\Desktop>size a.exe
text data bss dec hex filename
4260 4000940 96 4005296 3d1db0 a.exe
无变化!
“若把{1}改成{0}”的情况
C:\Users\tfans\Desktop>gcc test.c -g -O2
C:\Users\tfans\Desktop>size a.exe
text data bss dec hex filename
4260 940 4000120 4005320 3d1dc8 a.exe
无变化!
这是为啥?也就是说等于没优化,是表示编译器的算法对存储空间的”优化诱惑”抱有不灵敏的心态吗?
标签:
原文地址:http://www.cnblogs.com/wbstackpop/p/4293255.html