慕课网C#开发轻松入门 6-1练习题目
一次考试,各位同学的姓名和分数如下:
请编写程序,输出分数最高的同学的姓名和分数。运行效果如下:
方法一:
求最高分,实际上是一种查找算法,即查找“比已知的最高分更高的分数”。
建议你先声明2个数组分别存储姓名和分数,然后在分数数组中查找最高分,最高分找到了,对应的姓名自然也就找到了。
using System;
using System.Collections.Generic;
using System.Text;
namespace projGetMaxScore
{
class Program
{
static void Main(string[] args)
{
int i,k,max;
string[] name=new string[]{"吴松","钱东宇","伏晨","陈陆","周薇","林日鹏","何昆","关欣"};
int[] num=new int[]{89,90,98,56,60,91,93,85};
k=0;
max=num[0];
for(i=1;i<num.Length;i++)
{
if(num[i]>max)
{
max=num[i];
k=i;
}
}
Console.WriteLine("分数最高的是{0},分数是{1}",name[k],num[k]);
}
}
}
方法一核心代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyApp1 // 命名空间
{
class Program //类
{
static void Main(string[] args)
{
int[] num = new int[] {45,29,80,15,6,33 };
int max;//最大值
max = num[0];//初始化为第一个元素
int index=0;//最大值的索引
for (int i = 1; i < num.Length; i++)
{
if (num[i] > max)//如果发现了比max更大的数字,赋值给max
{
max = num[i];
index = i;//记录索引
}
}
Console.WriteLine("最大值是"+max+"索引是"+index);
}
}
}
方法二:
using System;
using System.Collections.Generic;
using System.Text;
namespace projGetMaxScore
{
class Program
{
static void Main(string[] args)
{
string[,] info = new string[8, 2] { { "吴松", "89" }, { "钱东宇", "90" }, { "伏晨", "98" }, { "陈陆", "56" }, { "周蕊", "60" }, { "林日鹏", "9" }, { "何昆", "93" }, { "关欣", "85" } };
string name="",score="0";
for(int i=0;i<8;i++)
{
if(String.Compare(info[i,1],score)>0)
{
score = info[i,1];
name = info[i,0];
}
}
Console.WriteLine("分数最高的是"+name+",分数是"+score);
}
}
}