算法竞赛入门经典,练习代码 ,4.4.1 小问题集锦

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

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

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

#include <stdio.h>
#include<assert.h>
typedef const double db;//常类型的变量或对象的值是不能被更新的
void solve(db a,db b, db c,db d, db e,db f,double *x,double *y)
{
   assert(a*e-b*d!=0.);
   //cout << a << b<<c<<d<<e<<f << endl;
   *x=(c*e-b*f)/(a*e-b*d);
   *y=(c*d-a*f)/(b*d-a*e);
   return;
}
void solve1(db a,db b,db c,db d,db e,db f){
    assert(a*e-b*d!=0);
    double x=0.,y=0.;
    x=(c*e-b*f)/(a*e-b*d);
    y=(c*d-a*f)/(b*d-a*e);
    printf("x=%.2lf\ny=%.2lf\n",x,y);
}
int main()
{
    double a=0.,b=0.,c=0.,d=0.,e=0.,f=0.,x=0.,y=0.;
    scanf("%lf %lf %lf %lf %lf %lf",&a,&b,&c,&d,&e,&f);
    {solve(a,b,c,d,e,f,&x,&y); //8 arguments
    printf("x=%.2lf\ny=%.2lf\n",x,y);}
    {solve1(a,b,c,d,e,f);}
    return 0;
}


ax+by=c
dx+ey=f
当a/d≠b/e 时,该方程组有一组解。
当a/d=b/e=c/f 时,该方程组有无数组解。
当a/d=b/e≠c/f 时,该方程组无解。
#include <stdio.h>
typedef const double db;//常类型的变量或对象的值是不能被更新的
int solve(db a,db b, db c,db d, db e,db f,double *x,double *y)
{
    int flag=1;
    if(a*e-b*d!=0.)
    {
        *x=(c*e-b*f)/(a*e-b*d);
        *y=(c*d-a*f)/(b*d-a*e);
    }
    else{
        if(c*e-b*f==0)
            flag=0;
        else
            flag=-1;
    }
   return flag;
}
int main()
{
    double a=0.,b=0.,c=0.,d=0.,e=0.,f=0.,x=0.,y=0.;
    int flag;
    scanf("%lf %lf %lf %lf %lf %lf",&a,&b,&c,&d,&e,&f);
    flag=solve(a,b,c,d,e,f,&x,&y);
    if(flag==1)
        printf("x=%.2lf\ny=%.2lf\n",x,y);
    else if(flag==0)
        printf("Unlimited answers");
    else
        printf("No answer");

    return 0;
}

编写一个程序包含3个函数f()、g()、和h(),3个函数均无参数,返回值均为int类型。
任务1:定义int a,b,要求在依次执行a=f()和b=f()后,a和b的值不同。
任务2:定义int a,b,要求在执行a=(f()+g())+h()和b=f()+(g()+h())后,a和b的值不同。
#include <stdio.h>
int k=0;
int f()
{
    return k++;
}
int main()
{
    int a,b;
    a=f();
    b=f();
    printf("a=%d b=%d",a,b);
    return 0;
}

#include<iostream>
using namespace std;
int k=4;
int f(){return (k=k*3);}
int g(){return (k=k-2);}
int h(){return (k=k/5);}
int main()
{
    int a,b;
    a=(f()+g())+h();
    b=f()+(g()+h());
    cout <<a <<" "<< b<<endl;
    return 0;
}

问题1:局部变量是否可以和局部变量重名?如果可以,实际上使用的是哪个?这可能会引起什么样的难以察觉到的错误?
问题2:如果在函数中声明一个局部变量,然后返回它的地址,调用者获取该地址时,该地址是否有效的?为什么?
 1:可以,局部

2:有效
#include<iostream>
using namespace std;

int* f(){
    int x=6;
    return &x;
}
int main()
{
    int* a;
    a=f();
    cout<<*a;
    return 0;
}
#include<iostream>
using namespace std;
int a=10;
int main()
{
    int a=3;
    a++;
    cout << a;
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值