写几个昨天没有提到的函数应用题目:
输入两个正整数,编程计算两个数的最小公倍数:
#include<iostream>
using namespace std;
int x,y;
int gcd(int x,int y)
{
int r=x%y;
while(r!=0)
{
x=y;
y=r;
r=x%y;
}
return y;
}
int lcm()
{
return x*y/gcd(x,y);
}
int main()
{
cin>>x>>y;
cout<<lcm()<<endl;
return 0;
}
编程输入十进制整数N(-32767~32767),请输出它对应的二进制、八进制、十六进制:
#include<cstdlib>
#include<iostream>
using namespace std;
void TurnData(int n,int a);
char ch[6]={'A','B','C','D','E','F'};
int main()
{
int n;
cin>>n;
TurnData(n,2);
TurnData(n,8);
TurnData(n,16);
return 0;
}
void TurnData(int n,int a)
{
int x[17],i,j,k=0;
cout<<n<<"turn into"<<a<<" :"<<endl;
if(n<0)cout<<'-';
j=abs(n);
do
{
k++;
i=j%a;
j/=a;
x[k]=i;
}
while(j!=0);
for(int h=k;h>=1;--h)
if(x[h]<10)cout<<x[h];
else cout<<ch[x[h]-10];
cout<<endl;
}
分数约分:
#include<iostream>
#include<iomanip>
using namespace std;
void common(int x,int y);
int main()
{
int a,b;
cin>>a>>b;
common(a,b);
}
void common(int a,int b)
{
int m=a,n=b,r;
do
{
r=m%n;
m=n;
n=r;
}while(r!=0);
a/=m;
b/=m;
cout<<setw(5)<<a<<setw(5)<<b<<endl;
}