4.4.1 小问题集锦
任务1:使用assert宏,让解不唯一时退出。
<span style="font-size:18px;"><span style="font-size:18px;"><strong>#include<stdio.h>
#include<assert.h>
void solve(double a,double b, double c,double d, double e,double f,double &x,double &y)
{
assert(a*e-b*d!=0.);
x=(c*e-b*f)/(a*e-b*d);
y=(c*d-a*f)/(b*d-a*e);
}
int main()
{
double a,b,c,d,e,f,x,y;
scanf("%lf%lf%lf%lf%lf%lf",&a,&b,&c,&d,&e,&f);
solve(a,b,c,d,e,f,x,y);
printf("x=%.3f,y=%.3f\n",x,y);
return 0;
} <strong>
</strong></span></strong></span>
任务2:解不唯一时仍然正常返回,但调用者有办法知道解的数量(无解、唯一解,无穷多组解)。
<span style="font-size:18px;">#include<stdio.h>
int solve();
double a,b,c,d,e,f,x,y;
int main()
{
int s;
scanf("%lf%lf%lf%lf%lf%lf",&a,&b,&c,&d,&e,&f);
s=solve();
if(s==1)
printf("x=%f,y=%f\n",x,y);
else if(s==-1)
printf("No answer.\n");
else
printf("countless answers.\n");
return 0;
}
int solve()
{
if(a*e-b*d==0.)
{
if(c*d-a*f==0.0)
return 0;
else
return -1;
}
else {
x=(c*e-b*f)/(a*e-b*d);
y=(c*d-a*f)/(b*d-a*e);
return 1;
}
} </span>
思考:
任务一:
定义int a,b,要求依次执行a=f(),b=f()后,a和b的值不同。
#include<stdio.h>
int i=1;
int f()
{
return i++;
};
int main()
{
int a,b;
a=f();
b=f();
printf("a=%d,b=%d\n",a,b);
return 0;
}<strong>
</strong>
任务二:定义int a,b,要求在依次执行a=(f()+g())+h()和b=(f()+(g()+h())后,a和b的值不同。
<span style="font-size:18px;">#include<stdio.h>
int i=1;
int f()
{
return (i=2*i);
}
int g()
{
return (i=i+2);
}
int h()
{
return (i=i-5);
}
int main()
{
int a,b;
a=(f()+g())+h();
b=f()+(g()+h());
printf("a=%d,b=%d\n",a,b);
return 0;
}</span>
问题一:局部变量是否可以和全局变量重名?如果可以,实际上用的是哪个?这可能会引起什么样的难以察觉到的错误?
当然可以重名,我们可以通过下面程序来看。
<span style="font-size:18px;">#include<stdio.h>
int a=1;
int main()
{
int a=2;
a++;
printf("a=%d\n",a);
return 0;
}</span>
运行结果如下图:
问题二:如果函数中声明一个局部变量,然后返回它的地址,调用者获得该地址时,该地址是否有效?为什么?
<span style="font-size:18px;">#include<stdio.h>
int *fun()
{
int a=1;
printf("a=%d\n",a);
return &a;
}
int main()
{
int *b=fun();
*b=2;
printf("*b=%d\n",*b);
return 0;
}</span>
从程序的结果看,好像是有效的。
实验一:声明全局变量int a[1000000],不要声明其他变量,编译后可执行文件大小。
<span style="font-size:18px;">#include<stdio.h>
int a[1000000];
int main()
{
return 0;
}<strong>
</strong></span>
实验二:声明全局变量int a[1000000]={1},不要声明其他变量,编译后查看可执行文件大小。
在我电脑里可执行文件的大小为3929KB.
<span style="font-size:18px;">#include<stdio.h>
int a[1000000]={1};
int main()
{
return 0;
}
</span>
我的电脑中可执行文件大小是23KB。
-------------写博客纯属记录自己学习过程,如有错误,还望诸位不吝赐教。