/*(1)定义一个函数 int count(int a[],int n) 在n个元素的数组a中,统计出大于零的元素个数,此个数作为函数返回值。 在main()函数中,对数组b做如下初始化
int b[]={15,16,-23,7,-5,19,-2,0,28,11};
然后调用你定义的函数,在主函数中输出数组b中小于零元素的个数。
*/
#include "iostream.h"
int z=0;//零的个数
int count(int a[],int n)
{
int dl=0; //大于0的个数
int i;
for(i=0;i<n;i++)
{
if(a[i]>0)
dl++;
else if(a[i]==0)
z++;
}
return dl;
}
void main()
{
int n,x;
int b[]={15,16,-23,7,-5,19,-2,0,28,11};
n=10;
x=n-count(b,n);
x=x-z;
cout<<"less than zero number="<<x<<endl;
}
/*(2)写两个函数,分别求两个整数的最大公约数和最小公倍数,
用主函数调用这两个函数并输出结果。两个整数由键盘输入。
利用最大公约数求最小公倍数
由于两个数的乘积等于这两个数的最大公约数与最小公倍数的积。这就是说,求两个数的最小公倍数,可以先求出两个数的最大公约数,再用这两个数的最大公约数去除这两个数的积,所得的商就是两个数的最小公倍数。
例 求105和42的最小公倍数。
因为105和42的最大公约数是21,
105和42的积是4410,4410÷21=210,
所以,105和42的最小公倍数是210。
*/
#include "iostream.h"
int gys,gbs;
int gy(int a,int b)
{
int r;
r=a%b;
if(r!=0)
{
a=b;
b=r;
r=a%b;
}
return b;
}
int gb(int a,int b)
{
int r;
r=a*b/gys;
return r;
}
int main()
{
int a,b,t;
cout<<"Input a"<<endl;
cin>>a;
cout<<"Input b"<<endl;
cin>>b;
if(a==0 || b==0)
{
cout<<"Input Error"<<endl;
return 0;
}
if(a<b)
{
t=a;a=b;b=t;
}
gys=gy(a,b);
gbs=gb(a,b);
cout<<"gys="<<gys;
cout<<"gbs="<<gbs;
}
/*(3)求方程ax2+bx+c=0的根,用三个函数分别求当b2-4ac大于0、
等于0和小于0时的根,并输出结果。从主函数出入a、b、c的值,
编程求解该方程的根。
*/
#include "iostream.h"
#include <math.h>
void dy(double a,double b,double c,double derta)
{
double d;
double x1,x2;
if(a==0)
{
x1=-c/b;
x2=-c/b;
}
else
{
d=pow(derta,0.5);
x1=(-b+d)/2/a;
x2=(-b-d)/2/a;
}
cout<<"x1="<<x1<<endl;
cout<<"x2="<<x2<<endl;
}
void deng(double a,double b,double c, double derta)
{
dy(a,b,c,derta);
}
void xiao(void)
{
cout<<"no answer!"<<endl;
}
int main()
{
double a,b,c;
double derta;
cout<<"Input a"<<endl;
cin>>a;
cout<<"Input b"<<endl;
cin>>b;
cout<<"Input c"<<endl;
cin>>c;
derta=b*b-4*a*c;
if( derta>0)
{
dy(a,b,c,derta);
}
else if(derta==0)
{
deng(a,b,c,derta);
}
else // derta<0
{
xiao();
}
}
/*(4)写一个判素数的函数,在主函数输入一个整数,输出是否素数的信息
*/
#include "iostream.h"
#include <math.h>
int compare(int n)
{
int b=1;
int i;
if(n==2 || n==1)
{
}
else
{
for(i=2;i<=n;i++)
{
if(n%i==0)
{
b=0;
break;
}
}
}
return b;
}
int main()
{
int n;
cout<<"Input n"<<endl;
cin>>n;
if(compare(n)==1)
{
cout<<"this number is prime number!"<<endl;
}
else
{
cout<<"this number is not prime number!"<<endl;
}
}
/*(1) 编写一个函数,实现两个整数的交换。如:主调函数中
int a=10;
int b=20;
使用引用作为函数的参数,交换后为:
a=20;
b=10;
*/
#include "iostream.h"
void change(int &a,int &b)
{
int t;
t=a;
a=b;
b=t;
}
void main()
{
int a=10;
int b=20;
change(a,b);
cout<<"a="<<a<<"\nb="<<b<<endl;
}
/*(2) 编程实现两个字符串的交换。如:
char *p1=”hello”
char *p2=”good”
使用引用作为函数的参数,交换后为:
p1: ” good”
p2:” hello”
*/
#include "iostream.h"
#include "stdio.h"
#include "string.h"
void change(char *&p1,char *&p2)
{
char *t1;
t1=p1;
p1=p2;
p2=t1;
}
void main()
{
char *p1="hello";
char *p2="good";
change(p1,p2);
cout<<"p1="<<p1<<"\np2="<<p2<<endl;
}
参考资料:用了一下午编出来了。下班前正好弄出来。编译在VC6下通过。