2009年苏州大学机试
第一题(20分)
题目
从键盘从键盘输入一组非零整数(以输入零作为输入结束的标志)
编程要求:
- 这组数的正数和负数的个数
- 这组数的和及平均值
代码
#include <iostream>
#include <sstream> //字符串流
using namespace std;
int main() {
const int MAX_SIZE = 100;
int Arr[MAX_SIZE];
int size = 0;
int Positive_integer = 0;
int Negative_integer = 0;
int Arr_Sum = 0;
double Ave_value = 0;
int Temp;
cout << "请输入一组非零整数(以空格分隔,输入0结束):" << endl;
//读取整行输入
string input;
getline(cin,input);
//使用字符串流解析整行输入
stringstream ss(input);
//输入数组操作
while (ss >> Temp && Temp != 0){
if (size < MAX_SIZE){
Arr[size] = Temp;
//判断正负
if (Temp > 0){
Positive_integer++;
} else{
Negative_integer++;
}
size++;
} else{
cout << "数组已满,无法添加更多元素。" << endl;
break;
}
}
//打印数组并求和
cout << "输入的非零数组为:";
for (int i = 0; i < size; ++i) {
Arr_Sum += Arr[i];
cout << Arr[i] << " ";
}
cout << endl;
//计算平均值
Ave_value = static_cast<double>(Arr_Sum) / size;
//打印结果
cout << "这组数正数为:" << Positive_integer << "个"
<< "负数为:" << Negative_integer << "个" << endl;
cout << "这组数的和为:" << Arr_Sum << ",平均值为:" << Ave_value << endl;
//清零
Positive_integer = 0;
Negative_integer = 0;
Arr_Sum = 0;
Ave_value = 0;
system("pause");
return 0;
}
结果
第二题(30分)
题目
从键盘输入一个4*4的矩阵A,
编程求:
- 矩阵A的两对角线元素之和
- 矩阵A的转置
- 从键盘输入另一个4*4的矩阵B计算矩阵A和B的乘积
代码
#include <iostream>
using namespace std;
int main() {
int Arr_A[4][4];
int Tran_Arr_A[4][4];
int Arr_B[4][4];
int Arr_AB[4][4];
int MainDiag_Sum = 0;
int SecondaryDiag_Sum = 0;
int MandS_Sum = 0;
cout << "请输入4*4矩阵A的元素:" << endl;
//输入矩阵元素:
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
cout << "请输入第 " << (i + 1) << " 行,第 " << (j + 1) << " 列的元素:";
cin >> Arr_A[i][j];
}
}
//输出矩阵
cout << "输入的矩阵为:" << endl;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
cout << Arr_A[i][j] << " ";
}
cout << endl;
}
//计算两对角线元素之和
for (int i = 0; i < 4; ++i) {
MainDiag_Sum += Arr_A[i][i];
SecondaryDiag_Sum += Arr_A[i][4 - 1 -i];
}
MandS_Sum = MainDiag_Sum + SecondaryDiag_Sum;
//输出两对角线元素之和
cout << "主对角线元素之和:" << MainDiag_Sum << endl;
cout << "副对角线元素之和:" << SecondaryDiag_Sum << endl;
cout << "两对角线元素之和:" << MandS_Sum << endl;
//矩阵A的转置
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
Tran_Arr_A[j][i] = Arr_A[i][j];
}
}
//输出矩阵A的转置
cout << "矩阵A的转置为:" << endl;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
cout << Tran_Arr_A[i][j] << " ";
}
cout << endl;
}
//输入矩阵B
cout << "请输入4*4矩阵B的元素:" << endl;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
cout << "请输入第 " << (i + 1) << " 行,第 " << (j + 1) << " 列的元素:";
cin >> Arr_B[i][j];
}
}
//计算矩阵A和B的乘积
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
Arr_AB[i][j] = 0;
for (int k = 0; k < 4; ++k) {
Arr_AB[i][j] += Arr_A[i][k] * Arr_B[k][j];
}
}
}
// 输出矩阵乘积
cout << "矩阵 A 和 B 的乘积为:" << endl;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
cout << Arr_AB[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
结果
声明
此代码为个人编写,题目来自互联网,使用平台为Clion,C++17标准。
由于博主才疏学浅,如有错误请多多指正,如有更好解法请多多交流!