任务一:
//编写递归函数将十进制数转换成二进制数输出。
#include <iostream>
using namespace std;
void d2d (int n);
int main (void)
{
int a; //输出十进制数
cin >> a;
d2d (a); //转换成二进制输出
cout << endl;
return 0;
}
void d2d (int n)
{
if (n == 0)
{
cout << 0;
}
else if (n == 1)
{
cout << 1;
}
else
{
d2d (n / 2);
cout << n % 2;
}
}
任务二:
//编程序输入m,n,输出组合数,要求用自定义函数求阶乘。
#include <iostream>
using namespace std;
long fac (int n); //求n的阶乘
int main (void)
{
int m, n; //存储组合数的上限下限
cin >> m >> n;
cout << fac (m) / fac (n) / fac (m - n) << endl;
return 0;
}
long fac (int n)
{
int s;
if (n == 1)
{
return 1;
}
else
{
s = n * fac (n - 1);
}
return s;
}
任务三:
3.1
//输入一行字符,统计其中有多少个单词。
#include <iostream>
#include <string.h>
using namespace std;
int main (void)
{
char input [50];
gets(input);
int num = 1; //储存单词个数
for (int i = 1; i < 50; ++i)
{
if ((input [i - 1] != ' ') && (input [i] == ' '))
{
++num;
}
}
cout << "There are " << num <<" words in the line." << endl;
return 0;
}
3.2
//输出规范的文本
#include <iostream>
#include <string.h>
using namespace std;
int main (void)
{
char input [50];
char cpyinput [50];
gets (input);
int c = 0; //区分单词与空格
for (int i = 0, j = 0; i < 50; ++i)
{
if (input [i] != ' ' && input [i] != '\0')
{
c = 1;
}
if (c == 1)
{
cpyinput [j] = input [i];
if (input [i] == '.' || input [i] == '!' || input [i] == ',' || input [i] == ';' || input [i] == '?')
{
cpyinput [j + 1] = ' ';
++j;
if (input [i + 1] == ' ')
{
++i;
}
}
++j;
}
if (input [i] == ' ')
{
c = 0;
}
}
cout << cpyinput << endl;
return 0;
}