练习

来源:互联网 发布:网络主播人气排行榜 编辑:程序博客网 时间:2024/04/29 05:17

1、输入两个整数,求它们的平方和

include<iostream>
using namespace std;
int fun2(int m)
{
return m*m;
}
int fun1(int x,int y)
{
return fun2(x)+fun2(y);
}
int main()
{
int a,b;
cout<<"please enter two integers(a and b):";
cin>>a>>b;
cout<<"The sum of square of a and b:"<<fun1(a,b)<<endl;
return 0;
}

2、求n!

#include<iostream>
using namespace std;
unsigned fac(unsigned n)
{
unsigned f;
if(n==0)
f=1;
else
f=fac(n-1)*n;
return f;
}
int main()
{
unsigned n;
cout<<"Enter a positive interger:";
cin>>n;
unsigned y=fac(n);
cout<<n<<"!="<<y<<endl;
return 0;
}

3、定义一个可以存放10个数据的数组,要求从键盘输入10个数据,最后按照逆序输出。

#include<stdio.h>
int main()
{
int a[10],i;
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=9;i>=0;i--)
printf("%d",a[i]);
printf("\n");
return 0;
}

4、以指定数据输入:

输入a和b计算它们的和。输入0 0代表测试数据结束,此行不做处理。
Sample input:
1 5
10 20
0 0
Sample output:
6
30

#include <stdio.h>
int main()
{
int a, b;
while (scanf(“%d%d”, &a,&b) &&(a != 0 && b != 0))

{
printf(“%d\n”, a + b);
}
return 0;
}

5、收假币问题

问题描述:一天有个年轻人来到王老板的店里买了一件礼物,这件礼物成本是p1元,标价p2(p2 >= p1)元.结果是这个年
轻人掏出m(m > p2)元要买这件礼物,王老板当时没有零钱,用那m元向街坊换了m元的零钱,找给年轻
人(m - p2)元.但是街坊后来发现那m元是假钞,王老板无奈还了街坊m元.现在问题是:
王老板在这次交易中到底损失了多少钱?(其中损失成本p1元,不要算成p2元)

程序如下:

#include<stdio.h>
int main()
{
int p1,p2,m,n;
while(scanf("%d%d%d",&p1,&p2,&m)!=EOF)
{
n=m-(p2-p1);
printf("%d\n",n);
}
return 0;
}

6、模拟顺序表操作

输入:一个班级10位同学的姓名,年龄。姓名为一个字符串,不超过20个字符。姓名和年龄直接用一个空格隔开。

输出:原样输出(测试一组数据)

程序如下:

#include<iostream>
#include<string>
using namespace std;
int main()
{
string name;
int age;
while(cin>>name>>age)
{
cout<<name<<" "<<age<<endl;
}
return 0;
}

注意:当题目中说:多组测试数据/处理到文件尾时,用while(scanf("%d",&n"!=EOF){};

当题目中说:有多组测试数据,第一行是一个整数T代表着测试数据的数量时,用scanf("%d",&T);while(T--)。
7、求两个数的最大公约数

#include<stdio.h>
int gcd(int n,int m)
{
int r;
while(n%m)
{
r=n%m;
n=m,m=r;
}
return m;
}
int main()
{
int a,b,c;
while(scanf("%d%d",&a,&b)!=EOF)
{
printf("%d\n",gcd(b,a));
}
return 0;
}

原创粉丝点击