Article Directory
1. There are parameters and inverse functions
Write two functions, the functions of which are: find the greatest common divisor and least common multiple of two integers
[Sample code]
#include<iostream>
using namespace std;
//最大公约数
int GCD(int a, int b)
{
int gcd;
int max = a;
if (a > b)
max = b;
for (int i = 1; i <= max; i++)
{
if ((a%i == 0) && (b%i == 0))
gcd = i;
}
return gcd;
}
//最小公倍数
int LCM(int a, int b)
{
int lcm;
int min = a;
if (a < b)
min = b;
for (int i = min; ; i++)
{
if ((i%a == 0) && (i%b == 0))
{
lcm = i;
break;
}
}
return lcm;
}
int main()
{
int a, b, gcd, lcm;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
gcd = GCD(a, b); //最大公约数
lcm = LCM(a, b); //最小公倍数
cout << "最大公约数是:" << gcd << endl;
cout << "最小公倍数是:" << lcm << endl;
system("pause");
return 0;
}
[Reference results]
2. Participation without return
Write the function factors (num, k). The function is to find the number of factors k contained in the integer num.
For example: 32=2 2 2 2 2, then factors(32,2)=5
[Sample code]
#include<iostream>
using namespace std;
void factors(int num, int k)
{
int i = 0;
while (1)
{
if (num%k == 0)
{
num = num / k;
i++;
}
else
break;
}
cout << "包含的因子数为:" << i << endl;
}
int main()
{
int num, k;
cout << "num = ";
cin >> num;
cout << "k = ";
cin >> k;
factors(num, k);
system("pause");
return 0;
}
[Reference results]
3. No participation and return
Find the length of a string
[Sample code]
#include<iostream>
#include<string>
using namespace std;
int char_long()
{
int len;
char a[50];
cout << "请输入一个字符串:";
cin.get(a,50);
len = strlen(a);
return len;
}
int main()
{
int len;
len = char_long();
cout << "字符串长度为:" << len << endl;
system("pause");
return 0;
}
[Reference results]
4. No participation, no return
[Sample code]
#include<iostream>
using namespace std;
void screen()
{
cout << "热爱可抵岁月漫长" << endl;
}
int main()
{
screen();
system("pause");
return 0;
}