c++基础

难理解的知识点

const char* pc = “abcd”;
能改地址不能改数据。
错误: pc【3】=‘x’;
允许: pc = “efgh”;

char* const pc = “abcd”;
能改数据不能改地址。
错误:pc = “efgh”;
正确:pc[3] = ‘x’;

const char * const pc = “abcd”;
既不能改地址,又不能改数据。

用动态分配空间的方法计算Fibonacci数列的前20项并储存到动态分布空间

代码

#include <iostream>

using namespace std;

 int main()
 {
     int *p;
     p=new int[20];
     p[0]=1;
     p[1]=1;
     for(int i=2;i<20;i++)
     {
         p[i]=p[i-1]+p[i-2];
     }
     for(int i=0;i<20;i++)
     {
         cout<<p[i]<<" ";
     }
     delete []p;
 }

现象
在这里插入图片描述

建立一个被称为sroot()的函数,返回其参数的二次方根。重载函数sroot()3次,让它返回整数,长整数与双精度二次方根(计算二次方根时,可以用标准库函数sqrt())

#include <iostream>
#include <cmath>
using namespace std;

int sroot(int x)
{
   x=sqrt(x);
   return x;
}

long sroot(long x)
{
   x=sqrt(x);
   return x;
}

double sroot(double x)
{
    x=sqrt(x);
   return x;
}

 int main()
 {

         int x=4;
         long y=256;
         double z=0.04;
         x=sroot(x);
         y=sroot(y);
         z=sroot(z);
         cout<<x<<endl;
         cout<<y<<endl;
         cout<<z<<endl;

 }

在这里插入图片描述

解决百钱问题:将一元人民币兑换成1,2,5分的硬币,有多少种换法?

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n=0;
    int x,y,z;
    for(x=0;x<=100;x++)
    {
        for(y=0;y<=50;y++)
        {
            for(z=0;z<=20;z++)
            {
                if(1*x+2*y+5*z==100)
                {
                    cout<<x<<" "<<y<<" "<<z<<endl;
                    n++;
                }
            }
        }
    }
    cout<<n<<endl;
}

541种

输入两个整数,将他们从小到大顺序排列。要求使用变量的引用

#include <iostream>
#include <cmath>
using namespace std;

void swap(int &x,int &y)
{
   if(x>y)
   {
       int temp;
       temp=x;
       x=y;
       y=temp;
   }
}

int main()
{
    int x,y;
    cin>>x>>y;
    swap(x,y);
    cout<<x<<" "<<y;
}

用二分法求解方程f(x)=0的根;

#include <iostream>
#include <cmath>

using namespace std;

float fan(float x)
{
    return x*x-3*x+2.0f;//f(x),在这里我们可以修改
}

float get(float a,float b,float c)
{
    if(fan(a)*fan(b)>0)
    {
        return 0.0f;//f(x)=0,只有一个值,并且在a,b,之间才能找到x
        //那么fan(a)*fan(b)<=0,才对
    }
    while(true)
    {
        float x = 0.5f*(a+b);//二分
        float f = abs(fan(x));//取值
        float tol = abs(b-a);//a和b之间的距离

        if(f<c||tol<c)//如果取值或者a和b之间的距离小于精确度
        {
            return x;
        }
        if(fan(x)*fan(a)<0)//在a和x之间
        {
            b=x;
        }
        else//在b和x之间
        {
            a=x;
        }
    }
}

int main()
{
    float a=1.0f;
    float b=3.0f;
    float c=1e-8;//a,b要在x的值中间,否则出错,c为精确度

    float x = get(a,b,c);
    cout<<"x= "<<x<<endl;//输出x的值
    return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值