1、输入一个5行5列的二维数组,编程实现:
(1)求出其中的最大值和最小值及其对应的行列位置.
(2)求出对角线上各元素之和.
数组例如 : int[,] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25} };
const int m = 5;
const int n = 5;
int[,] arr = new int[5, 5];
for (int i = 0; i < m; i++) { //循环输入
for (int j = 0; j < n; j++) {
arr[i,j]=int.Parse(Console.ReadLine ());
}
}
int max = arr [0, 0], max_i = 0, max_j = 0;
int min = arr [0, 0], min_i = 0, min_j = 0;
int sum = 0;
for (int i = 0; i < m; i++) { //循环输入
for (int j = 0; j < n; j++) {
if (max<arr[i,j]) {
max = arr[i,j];
max_i = i;
max_j = j;
}
if (min>arr[i,j]) {
min = arr[i,j];
min_i = i;
min_j = j;
}
if (i ==j) {
sum += arr [i, j];
}
}
}
Console.WriteLine ("max={0},x={1},y={2}",max,max_i,max_j);
Console.WriteLine ("min={0},x={1},y={2}",min,min_i,min_j);
Console.WriteLine ("sum={0}",sum);
2. 求{"a","ba","bc","bad","abcde"}这个字符串数组中,字母a出现的次数
string[ ] arr = new string[ ]{"a","ba","bc","bad","abcd"};
string[ ] strArr = {"a","ba","bc","bad","abcd"};
int number = 0;
foreach (string str in strArr) {
char[ ] chars = str.ToCharArray ();
foreach(char ch in chars){
if (ch == 'a') {
++number;
}
}
}
Console.WriteLine ("number={0}",number);
3. 有一行英文语句,统计其中的单词个数(规定:单词之间以空格分隔),并将每一个单词的第一个字母改为大写
string str = "hello,my name is Yourfather";
// string[ ] strArr = str.Split (' '); //用空格分割开
// string new_str = str.Trim(); //把字符串头尾空格去掉
int number = 0;
char[ ] charArr = str.ToCharArray (); // 生成一个新的数组 字符串转为 字符数组
for (int i = 0; i < str.Length; i++) {
char ch = str.ToCharArray ()[i]; //把str下每个数单独赋值给ch
if (i == 0) { //定义第一个字母
if (ch >= 97 && ch <= 122) { //如果第一个字母为小写
charArr [i] = (char)(ch - 32); //转化为大写
}
}
if (ch == ' ') {
number++;
char next_ch = str.ToCharArray() [i + 1]; //空格后一位
if (next_ch>=97 && next_ch<=122) { //检查是否为小写字母
charArr [i + 1] = (char)(next_ch - 32);
}
}
}
// string new_str = new string (charArr);
string new_str = "";
foreach (char ch in charArr) {
new_str +=ch.ToString();
}
Console.WriteLine(new_str);
4. 求二维数组{{1,2,3},{4,5,6},{7,8,9}}的鞍点。
(鞍点:在行中最大,在列中最小的元素的位置,二维数组也可能没有鞍点)
1 2 3
4 5 6
7 8 9
int[,] arr = {{1,2,3},{4,5,6},{7,8,9}};
int max_i = 0, max_j = 0;
for (int i = 0; i < 3; i++) {
int max = 0;
for (int j = 0; j < 3; j++) { //确定数组中最大值坐在行和列
if (max < arr[i,j]) {
max = arr[i,j];
max_i = i; //2 定义最大值的下标
max_j = j; //2
}
}
bool isSaddlePoint = true; //定义鞍点值为真
for (int k = 0; k < 3; k++) { //确定最大值所在列数
if (max>arr[k,max_j]) { //判断列数中最大值
isSaddlePoint = false;
}
}
if (isSaddlePoint) {
Console.WriteLine ("有鞍点:{0},{1}",max_i,max_j);
}
}
网友评论