第三次上机作业
1、
#include<iostream>
using namespace std;
int main() {
int arr[3][3], t,s1=0;
for (int i = 0; i <3; i++) {
for (int j = 0; j < 3; j++)
cin >> arr[i][j];
}
for (int a = 0; a <3; a++) {
int s2 = 0;
for (int b = 0; b <3; b++) {
if (a == 0)
s1 += arr[a][b];
s2 += arr[a][b];
if (s1 <= s2) {
s1 = s2;
t = a;
}
}
}
if (t == 1)
return 0;
int arr2[3];
for (int i = 0; i <3; i++) {
arr2[i] = arr[0][i];
arr[0][i] = arr[t][i];
arr[t][i] = arr2[i];
}
for (int i = 0; i <3; i++) {
for (int j = 0; j < 3
; j++)
cout << arr[i][j];
cout << endl;
}
return 0;
}
2、
#include<iostream> using namespace std; int main() { int arr[3][3]; for (int a = 0; a < 3; a++) for (int b = 0; b < 3; b++) cin >> arr[a][b]; int s1=0, up=0, down=0; int *p = &arr[0][0]; for (int a = 0; a < 3; a++) { for (int b=0; b < 3; b++) { if (b == a) s1 += *p; if (b > a) up += *p; if (b < a) down += *p; p++; } } cout << "主对角线的元素和为:" << s1 << endl; cout << "上三角形的元素和为:" << up << endl; cout << "下三角形的元素和为" << down << endl; return 0; }
3、length能输出string的实际字符数,而sizeof输出的是string的占用空间。
isalpha是我在网上查的判断是否为字母的函数需要引用string库,实际上应该用那个阿斯克码的。
#include<iostream>
#include<cstring>
#include<cctype>
#include<string>
using namespace std;
int main() {
string s,s2;
int a = 1;
cin >>s;
int len = s.length();
int t = 0;
for (int i = 0; i < len; i++) {
if (isalpha(s[i])) {
s2.push_back (s[i]);
t++;
}
}
for (int i = 0; i < t / 2; i++) {
if (s2[i] >= 65 & s[i] <= 90)
{
s2[i] = s2[i] + 32;
}
if (s2[t - i - 1] >= 65 & s2[t - i - 1] <= 90) {
s2[t - i - 1] = s2[t - i - 1] + 32;
}
if (s2[i] != s2[t-1 - i]){
a = 0;
}
}
if (a)
cout << "The string is a palindrome" << endl;
else
cout << "The string is not a parlindrome" << endl;
}
4、我把计算机想象成一个住着导盲杖的盲人,拿着盲杖不断向前试探,每一个“1”代表一个石头,探到三个石头就把第三个石头踢掉,到头了再回来探,这就是我的大致思路。
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n=10;
int arr[10];
for (int i = 0; i < n; i++)
arr[i] = 1;
int m = (rand()+2)%10, t = 0;
while (1) {
for (int p = 1; p <= m;) {
if (arr[t % 10] == 1) {
p++;
}
t++;
}
arr[(t - 1)%10] = 0;
vector<int>vec;
int k = 0;
for (int j = 0; j <10; j++) {
if (arr[j] == 1) {
vec.push_back(arr[j]);
k++;
}
}
int s = vec.size();
if (s==1)
break;
}
for (int i = 0; i < n; i++) {
if (arr[i] == 1)
cout << "最后留下的序数为" << i+1;
}
return 0;
}