键盘输入若干整数(遇负数结束),要求将其中的偶数输出(每行3个偶数)并输出偶数的平均值(小数点后面保留2位)。 要求1:分别用for循环和while循环实现。(注:编写两个源程序) 要求2:提交截图(含源代码及运行结果) 示例: 输入:2 3 4 6 17 82 15 12 -9 输出:2 4 6 82 12 这些偶数的平均值是:21.20 提示:2和82是左对齐 提交
时间: 2023-05-25 13:03:12 浏览: 46
for循环实现:
#include<iostream>
using namespace std;
int main()
{
int n, sum = 0, cnt = 0;
for(int i=1;i<=100;i++) //循环100次防止死循环
{
cin >> n;
if(n<0) break; //遇负数结束输入
if(n%2==0) //如果是偶数
{
cout << n << "\t"; //输出
cnt++; //统计偶数数目
sum += n; //累加偶数之和
if(cnt%3==0) cout << endl; //每输出3个一换行
}
}
cout << endl << "这些偶数的平均值是:" << fixed << setprecision(2) << (double)sum/cnt;
return 0;
}
while循环实现:
#include<iostream>
using namespace std;
int main()
{
int n, sum = 0, cnt = 0;
cin >> n;
while(n>=0)
{
if(n%2==0)
{
cout << n << "\t";
cnt++;
sum += n;
if(cnt%3==0) cout << endl;
}
cin >> n;
}
cout << endl << "这些偶数的平均值是:" << fixed << setprecision(2) << (double)sum/cnt;
return 0;
}