2023C++电子 0224038 雷可
p124 T42
/*编写一个函数int Count(double a[],int n,)统计出具有n个元素的一维数组中
大于等于所偶有元素平均值的元素个数并返回这个之。注意:请使用for循环实现
该函数
*/
#include<stdio.h>
int count(double a[], int n)
{
int j = 0, i;
double c,b = 0;
for (i = 0; i < n; i++)
{
b += a[i];
}
c = b / n;
for (i = 0; i < n; i++)
{
if (a[i] >= c)
{
j = j + 1;
}
}
return j;
}
int main()
{
double a[100];
int i, x;
printf("请输入x的值,x=");
scanf_s("%d", &x);
printf("\n请输入%d个数:", x);
for (i = 0; i < x; i++)
{
scanf_s("%lf", &a[i]);
}
printf("这个大于等于所有元素平均值的元素个数为%d\n", count(a, x));
return 0;
}
p124 T47
/*请编写一个函数comm(int n, int k),用递归算法计算从n个人中
选择k个人组成一个委员会的不同组合数,由n个人里选k个人的组合
数=由(n-1)个人里选k个人的组合数+由(n-1)个人里选(k-1)个人的组合数
*/
#include <iostream>
using namespace std;
unsigned n, k, m, s, f, w;
unsigned fac1(unsigned s)
{
if (s == 0)
f = 1;
else
f = fac1(s - 1) * s;
return f;
} //设置阶乘函数fac1
unsigned fac2(unsigned n, unsigned k)
{
if (n == k || k == 0)
m = 1;
else if (k > n)
m = 0;
else
m = fac1(n) / (fac1(n - k) * fac1(k));
return m;
} //设置二项式函数fac2
int main() {
cout << "输入 n 和 k:" << endl;
cin >> n;
cin >> k;
w = fac2(n, k);
cout << "从" << n << "个人中选取" << k << "个人组成一个委员会共有" << w << "种组合" << endl;
return 0;
}
p125 T51
/*将数组a[n]中的每一个元素依次向后移动一位*/
#include <stdio.h>
int main()
{
int a[100] = { 0 };
int n, m;
scanf_s("%d%d", &n, &m);
for (int i = 0; i < n; i++)
{
scanf_s("%d", &a[i]);
}
for (int i = n - 1; i >= 0; i--)
{
a[i + m] = a[i];
}
for (int i = 0; i < m; i++)
{
a[m - i - 1] = a[n + m - i - 1];
}
for (int i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
p125 T53
/*编写函数,给出年月日后,求该日是该年的第几天*/
#include<stdio.h>
int flag(int year)//判断是否是闰年
{
int s = 0;
if (year % 4 == 0 && year % 400 != 0 || year % 100 == 0 && year % 400 == 0)
s = 1;
return s;
}
int date(int mon, int day)//计算时间天数
{
int s = 0;
int a[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
for (int i = 0; i < mon - 1; i++)
s = s + a[i];
s = s + day;
return s;
}
int main()
{
int year, mon, day, sum, p;
printf("输入日期:\n");//键盘输入日期
scanf_s("%d%d%d", &year, &mon, &day);
sum = date(mon, day);//计算天数
p = flag(year);
if (mon >= 3 && p == 1)//闰年要多一天
sum++;
printf("%d年%d月%d日是这一年的第%d天\n", year, mon, day, sum);
}