[C# introductory exercises and answers]

cycle

Loop structure (1)

1. In order to help Zhang Hao improve his grades as soon as possible, the teacher arranged daily learning tasks for him, including reading textbooks and studying theoretical parts in the morning, and doing computer programming and mastering the code part in the afternoon. Teachers check learning results every day. If not qualified, proceed.

Console.WriteLine("合格了吗?(y/n)");
char answer = char.Parse(Console.ReadLine());
while (answer=='n')
{
    
    
      Console.WriteLine("上午阅读");
      Console.WriteLine("下午编程");
      Console.WriteLine("及格了吗?(y/n)");
      answer =char.Parse(Console.ReadLine());
}
Console.WriteLine("完成学习任务!");
  1. In 2006, 80,000 trainees were trained, with an annual growth rate of 25%. At this growth rate, in which year will the number of trainees reach 200,000?
int year = 2006;
double student = 80000;
while (student < 200000)
{
    
    
    student = student + (student * 0.25);
    year++;
}
Console.WriteLine("在第{0}年达到20万人", year);
  1. After several days of study, the teacher gave Zhang Hao a test question and asked him to write a program on the computer and then the teacher checked whether he passed the test. If not, continue writing.
char answer;
do{
    
    
     Console.WriteLine("上机编程");
     Console.WriteLine("合格了吗?");
     answer = char.Parse(Console.ReadLine());
} while (answer=='n');
Console.WriteLine("恭喜你通过了测试!");

4. Use do-while to implement: output a comparison table between Celsius temperature and Fahrenheit temperature. It is required that it ranges from 0 degrees Celsius to 250 degrees, with an item every 20 degrees, and there are no more than 10 entries in the comparison table.
Conversion relationship: Fahrenheit = Celsius * 9 / 5.0 + 32
Tips:
1. Loop operation: calculate the Celsius temperature and output the comparison entry
2. Loop condition: entry <=10 && Celsius <= 250

double sheshi = 0;
int tiaomu = 0;
do
{
    
    
     double huashi = sheshi * 9 / 5.0 + 32;
     Console.WriteLine("摄氏温度 {0}   华氏温度{1}", sheshi,huashi);
     sheshi += 20;
     tiaomu++;
} while (tiaomu < 10 && sheshi <= 250);

Loop structure (2)

1. Implement integer reversal

            Console.WriteLine("请输入一个整数:");
            int i = int.Parse(Console.ReadLine());
            Console.WriteLine("反转之后得:");
            while (i!=0)
            {
    
    
                int b = i % 10;     //求余
                Console.Write(b);
                i = i /10;
            }


2. Loop through a student’s S1 final exam scores for 5 courses and calculate the average score.

for (int i = 0 ; i < 5 ; i++) {
    
      	//循环5次录入5门课成绩
Console.Write("请输入5门功课中第{0}门课的成绩: ", i +1 );
score = int.Parse(Console.ReadLine());  	//录入成绩
sum = sum + score;        	//计算成绩和
}
avg = (double)sum / 5;                      //计算平均分
Console.WriteLine(  "的平均分是:{0}" , avg);

3. Output the addition table as shown in the figure
Insert image description here

for(  int i = 0,  j = val;  i<=val;  i++,  j-- ){
    
    
        Console.WriteLine("{0} + {1} = {2}" , i , j , i+j );
 }

4. Find the sum of numbers between 1 and 100 that are not divisible by 3

            Console.WriteLine("1~100不能被3整除的数之和为:");
            int sum = 0;
            for(int i=0; i < 100; i++)
            {
    
    
                if (i % 3 != 0)
                {
    
    
                    sum += i;
                }
                
            }
            Console.WriteLine(sum);

5. Enter the scores of a student's 5 courses in a loop and calculate the average score. If a certain score is entered as negative, the entry will be stopped and an entry error will be prompted.

  			int score;
            int sum=0;
            for (int i = 0; i < 5; i++)
            {
    
           //循环5次录入5门课成绩  
                Console.Write("请输入第" + (i + 1) + "门课的成绩: ");
                score = int.Parse(Console.ReadLine());
                if (score < 0)
                {
    
          //输入负数
                    bool isNegative = true;
                    Console.WriteLine("录入错误");
                    break;
                }
                sum += score;         //累加求和
                }

6. Add integers between 1 and 10 to get the current number with a cumulative value greater than 20.

            int sum = 0;//存储总和
            for (int i = 1; i <= 10; i++)
            {
    
    
                sum += i;
                if (sum >= 20)//总和大于等于20
                {
    
    
                    Console.WriteLine("加到{0}的时候,总和大于了20", i);
                    break;//条件成立跳出循坏
                }
            }

7. Enter the students' scores in C# class in a circular manner, and count the proportion of students with scores greater than or equal to 80 points.

		    int total=10;
            int score;
            int num=0;
            for (int i = 0; i < total; i++)
            {
    
    
                Console.Write("请输入第{0}位学生的成绩:", i + 1);
                score = int.Parse(Console.ReadLine());
                if (score < 80)
                {
    
    
                    continue;//跳出本次循环,执行下一次循环
                }
                num++;
            }
            Console.WriteLine("80分以上的学生人数是: {0}", num);
            double rate = (double)num / total * 100;
            Console.WriteLine("80分以上的学生所占的比例为:{0}%", rate);

Loop structure (advanced)

  • Simulated mall shopping
  • Output the multiplication table

1. The English songs in the array are arranged in ascending order by name. Add a new song and keep the song names in ascending order

	String[ ] musics = new String[]{
    
    "Island","Ocean","Pretty","Sun"};
	String[ ] newMusics = new String[musics.length+1];//新歌曲数组
	String music = "";	//保存用户输入的歌曲名称
	……
	for(int i = 0; i < musics.length; i++){
    
    
		if(musics[i].CompareTo (music) > 0){
    
    
			index = i;
			break;
		}
	}
	for(int i = newMusics.length-1; i > index; i--){
    
    
		newMusics[i] = newMusics[i-1];  
	}
	newMusics[index] = music;    
	……

2. 4 students from each of the 3 classes will participate. Calculate the average score of the participating students in each class.

PS: Use the outer loop to control the number of classes, and the inner loop to control the number of students in each class.

			int classNum=3;
			double sum;
			double[] score = new double[3];
			double[] aver = new double[3];
			for (int i = 0; i< classNum; i++)
			{
    
    
				sum = 0.0;
				Console.WriteLine("请输入第{0}个班级的成绩", i + 1);
				for (int j = 0; j < score.Length; j++)
				{
    
    
					Console.Write("第{0}个学员的成绩:", j + 1);
					score[j] = int.Parse(Console.ReadLine());
					sum = sum + score[j];
				}
				aver[i] = sum / score.Length;           //计算平均分
				Console.WriteLine("第{0}个班级平均分{1}\n",i+1, aver[i]);
			}

3. There are 4 students in each of the 3 classes. Calculate the average score of the participating students in each class and count the number of students with scores greater than 85.
Requirement: Use continue to count the number of students >85.

			int classNum=3;
			double sum;
			double[] score = new double[3];
			double[] aver = new double[3];
			int count=0;
			for (int i = 0; i < classNum; i++)
			{
    
    
				sum = 0.0;
				Console.WriteLine("请输入第{0}个班级的成绩", i + 1);
				for (int j = 0; j < score.Length; j++)
				{
    
    
					Console.Write("第{0}个学员的成绩:", j + 1);
					score[j] = int.Parse(Console.ReadLine());
					sum = sum + score[j];
					if (score[j] < 85)
					{
    
    
						continue;
					}
					count++;

				}
				aver[i] = sum / score.Length;           //计算平均分
				Console.WriteLine("第{0}个班级平均分{1}\n",i+1, aver[i]);
				Console.WriteLine("高于85分的学员有{0}个\n",count);

4. Use * to print the right triangle pattern

		int rows = 3;					 //三角形行数
		Console.WriteLine("打印直角三角形");
		for(int i = 0; i < rows; i++){
    
        //打印第i行
			for(int j = 0; j <= i; j++){
    
      //打印i个*号
				Console.Write("*");
			}
			Console.Write("\n");	 //换行
		}

5. There are 5 clothing stores, and each store can buy up to 3 items. Users can choose to leave and buy clothes. Finally, print the total number of clothes bought.
Tip: Double loop solves the outer loop control. Go to the upper loop in each store to control the process of buying clothes. Use break to exit the inner loop.

			char choice;
			int count = 0;
			for (int i = 0; i < 5; i++)
			{
    
    
				Console.WriteLine("欢迎光临第{0}家专卖" , i + 1);
				for (int j = 0; j < 3; j++)
				{
    
    
					Console.WriteLine("要离开吗(y/n)?");
					choice = char.Parse(Console.ReadLine());
					if ('y'.Equals(choice))
					{
    
    
						break;
					}
					Console.WriteLine("买了一件衣服");
					count++;    //计数器加1
				}

6. Implement the multiplication table

		int rows = 9;	//乘法表的行数
		for(int i = 1; i<=rows; i++){
    
    	//一共9行
			for(int j = 1; j <= i; j++){
    
    	
				Console.Write(j+"*"+i+"="+j*i+"	");    
			}
			Console.Write("\n");			
		}
	}

array

1. Calculate the average score of the whole class

			int[] scores = new int[5];  //成绩数组
			int sum = 0;            //成绩总和

			Console.WriteLine("请输入5位学员的成绩:");
			for (int i = 0; i < scores.Length; i++)
			{
    
    
				scores[i] = int.Parse(Console.ReadLine());
				sum = sum + scores[i];  //成绩累加
			}
			Console.WriteLine("平均分是{0}", (double)sum / scores.Length);

2. Enter the scores of 5 students in a loop, sort them in ascending order and then output the results.

			int[] a = new int[5];
			int t;
			Console.WriteLine("请输入五位学生的成绩:");
			for (int i = 0; i < a.Length; i++)
			{
    
    
				a[i] = int.Parse(Console.ReadLine());//循环录入
			}


			for (int j = 0; j < a.Length - 1; j++)//冒泡排序
			{
    
    
				for (int k = 0; k < a.Length - j - 1; k++)
				{
    
    
					if (a[k] > a[k + 1])
					{
    
    
						t = a[k + 1];
						a[k + 1] = a[k];
						a[k] = t;
					}
				}
			}

			Console.Write("学员成绩升序排列 : ");
			for (int i = 0; i < a.Length; i++)
			{
    
    
				Console.Write("{0} ", a[i]);
			}

3. Enter the scores of the five students in this Java exam from the keyboard and find the highest score.

			int[] a = new int[5];
			int i,max;
			max = a[0];
			Console.WriteLine("请输入五位学生的成绩:");
			for ( i = 0; i < a.Length; i++)
			{
    
    
				a[i] = int.Parse(Console.ReadLine());//循环录入
			}

			for (i = 1; i < a.Length; i++)//打擂台法比较
			{
    
    
				
                if (max < a[i])
                {
    
    
					max = a[i];
                }
			}

			Console.Write("学员成绩最高分 :{0}",max);

classes and objects

1. In different training centers, you will feel the same environment and teaching atmosphere, and use similar ideas to output central information
Insert image description here

class School
		{
    
    
			public string schoolName;       //中心名称
			public int classNumber;            //教室数目
			public int labNumber;           //机房数目

			//定义教室的方法
			public void showCenter()
			{
    
    
				Console.WriteLine("{0}培训学员\n配备:{1}教室数目{2}机房数目",schoolName, classNumber, labNumber);
			}
		}

2. Create the "Beijing Center" object

class InitialSchool {
    
    
	static void Main(string[] args)
        {
    
    

			
				School center = new School();
				Console.WriteLine("***初始化成员变量前***");
				center.showCenter();
				center.schoolName = "北京中心";
				center.classNumber = 10;
				center.labNumber = 10;
				Console.WriteLine("\n***初始化成员变量后***");
				center.showCenter();
			
		}
}

3. Write the student class and output student-related information;Insert image description here

public class Student {
    
    
	String name;	//姓名
	int age;			//年龄
	String classNo;	//班级
	String hobby;	//爱好
	//输出信息方法
	public void show(){
    
    
		Console.WriteLine({
    
    0}\n年龄:{
    
    1}\n就读于:{
    
    2}\n爱好:{
    
    3}" , name, age, classNo ,hobby);
	}
}
class InitialStudent {
    
    
	 static void Main(String [] args){
    
    
		Student student = new Student();	
		student.name = "张浩";		
		student.age = 10;
		student.classNo = "S1班";
		student.hobby = "篮球";
		student.show();		               	
	}
}

4. A scenic spot charges different prices for tickets based on the age of the tourists. Please write the tourist class, determine the ticket price that can be purchased according to the age group and output
Insert image description here

class Visitor {
    
    
	public string name;		//姓名
    public int age;			//年龄
	//显示信息方法
	public void show(){
    
    
			if(age>=18 && age<=60){
    
    		//判断年龄
				Console.WriteLine({
    
    0}年龄为{
    
    1},价格为20元" ,name,age);
			}else{
    
    
				Console.WriteLine({
    
    0}的年龄为:{
    
    1},免费“,name,age);				}
	}
}
class InitialVistor {
    
    
	static void main(string[] args) {
    
    		
		Visitor v = new Visitor();		
		Console.Write("请输入姓名:");
		v.name = Console.ReadLine();			
		Console.Write("请输入年龄:");
		v.age = int.Parse(Console.ReadLine());		
		v.show();                       
	}
}

5. Modify the student's name, enter the new and old names, make the modification and display whether the modification is successful.

  public class StudentsBiz {
    
    
	  string[ ] names = new string[30]; 
	  public bool editName (string oldName,string newName) {
    
    
		  bool find = false;  // 是否找到并修改成功标识		
		  // 循环数组,找到姓名为oldName的元素,修改为newName
		  for(int i=0;i<names.length;i++){
    
    
			  if(names[i].Equals(oldName)){
    
    
				  names[i] = newName;
				  find=true;
				  break;
			  }
		  }
		  return find;
	  }
	}
  public class TestModify {
    
    
	  public static void Main(string[] args) {
    
    
	      ……
		  Console.Write("\n请输入要修改的学生姓名:");
		  string oldname = Console.ReadLine();
		  Console.Write("\n请输入新的学生姓名:");
		  string newname = Console.ReadLine();
		  Console.WriteLine("\n*****修改结果*****");
		  if( st.editName(oldname, newname) ){
    
    
			  Console.WriteLine("找到并修改成功!");
		  }else{
    
    
			  Console.WriteLine("没找到该学生!");
		  }
		  st.showNames();	
	  }
}

6. Specify the search range, search for student names and display whether the modification is successful

public bool searchName (int start,int end,string name){
    
    
	bool find = false;  // 是否找到标识
	// 指定区间数组中,查找姓名
	for(int i=start-1;i<end;i++){
    
    
	      if(names[i].Equals(name)){
    
    	
		  find=true;
		  break;
	      }
	}
	return find;
}
if(st.searchName(s,e,name)){
    
    
	Console.WriteLine("找到了!");
}else{
    
    
	Console.WriteLine("没找到该学生!");
}

Guess you like

Origin blog.csdn.net/QwwwQxx/article/details/129476317