难理解的知识点
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;
}