参考:https://blog.youkuaiyun.com/Artprog/article/details/54791429

第一小题:略
第二小题: 输入一些数,求最大值、最小值和平均数
本题关键是first的设置,使max,min只赋值一次,后置0
我用的是windows64位操作系统,按Ctrl+D回车结束输入
#include <iostream>
using namespace std;
int main()
{
int n,max,min,sum=0,cnt=0,first=1;
double mean = 0;
while (scanf("%d\n",&n)==1)
{
if (first)
{
max = min = n;
first = 0;
}
if (n > max)
{
max = n;
}
if (n<min)
{
min = n;
}
sum += n;
++cnt;
}
mean = sum * 1.0 / cnt;
cout << "最大值:" << max << " " << "最小值:" << min << " " << "平均值:" << mean << endl;
//system("pause");
return 0;
}
第三小题:输入一些数,哪两个数最接近。
这道题,关键是for循环的设置,因为是一维数组,也要用两重循环去遍历,第一个for循环是遍历到 <lenght(array)-1(倒数第二个元素)就停止了,而第二次for是遍历到<lenght(array)(最后一个元素才停止)
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int array[100], i, j, len = 0;
while (scanf("%d",&array[len])==1)
{
++len;
}
int a, b;
int distance = abs(array[0]-array[1]);
for (i = 0; i < len-1; i++)
{
for (j = i + 1; j < len; j++)
{
if (abs(array[i]-array[j])<distance)
{
a = array[i];
b = array[j];
distance = abs(array[i] - array[j]);
}
}
}
cout << "这两个数是:" << a << " " << b << ",接近值为:" << distance << endl;
//system("pause");
return 0;
}
第四小题:输入一些数,求第二大的值。
把两个数比较大小并赋值,?:在这很好
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int max, second, n;
cin >> max >> second;
int t1 = max > second ? max : second;
int t2 = max < second ? max:second;
max = t1;
second = t2;
while (scanf("%d", &n) == 1)
{
if (n>max)
{
second = max;
max = n;
//大于最大了,赶紧下一次循环
continue;
}
if (n>second&&n!=max)
{
second = n;
}
}
cout << "max:" << max << " " << "second:" << second << endl;
//system("pause");
return 0;
}
第五小题:输入一些数,求它们的方差。
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int sum=0,ct=0,a[100];
while (scanf("%d",&a[ct])==1)
{
sum += a[ct];
++ct;
}
double mean = sum*1.0 / ct;
double sum_tmp=0;
for (int i = 0; i < ct; i++)
{
double tmp = pow((a[i] - mean),2);
sum_tmp += tmp;
}
double fc = sum_tmp / ct;
printf("方差: %.3f\n", fc);
//system("pause");
return 0;
}
第六小题:输入一些数,统计不超过平均数的个数。
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int sum=0,ct=0,a[100];
while (scanf("%d",&a[ct])==1)
{
sum += a[ct];
++ct;
}
double mean = sum*1.0 / ct;
int ct2=0;
for (int i = 0; i < ct; i++)
{
if (a[i]>mean)
{
++ct2;
}
}
cout << "超过:" << ct2 << " 个"<<endl;
//system("pause");
return 0;
}
总结:2 3 4 道题比较好
本文详细介绍了使用C++进行数组操作的六种实用技巧,包括求最大最小值、寻找最接近的两个数、求第二大值、计算方差、统计不超过平均数的个数等,深入解析了每种技巧的实现思路和代码细节。
2565

被折叠的 条评论
为什么被折叠?



