1. 程式人生 > >一個c#程式碼

一個c#程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace experment5_1
{
    class Program
    {
        //Student類包含學生的所有必要資訊
        //以及關於這些資訊的計算方法,以及輸出學生資訊的方法
        class Student
        {
            public string stuNumber;    //
學號 public string stuName; //姓名 public int[] scores; //分數 public int[] scorePoint; //分數對應的點數 public Course[] courses; //參加的課程 public double staGPA; //標準GPA public double ordGPA; //一般GPA public Student() { } public
Student(string name, string number) //建構函式過載 { stuName = name; stuNumber = number; } public void setScore(int[] score) //設定學生的分數 { scores = new int[score.Length]; //例項化scores陣列 for (int i = 0
; i < score.Length; i++) scores[i] = score[i]; } public void setPoint() //設定學分點數 { scorePoint = new int[scores.Length]; //例項化scorepoint陣列 for (int i = 0; i < scores.Length; i++) if (scores[i] >= 90) scorePoint[i] = 4; else if (scores[i] >= 80) scorePoint[i] = 3; else if (scores[i] >= 70) scorePoint[i] = 2; else if (scores[i] >= 60) scorePoint[i] = 1; else scorePoint[i] = 0; } public void setCourse(Course[] course) //設定學生參加的課程 { courses = new Course[course.Length]; //例項化courses陣列 for (int i = 0; i < course.Length; i++) courses[i] = course[i]; } public void calGPA() //計算標準GPA和常見GPA { //此函式中要使用scorePoint,所以在使用前要先呼叫setPoint()函式 //否則會提示未將物件引用例項化 setPoint(); int sumSta = 0; int sumOrd = 0; int sumCre = 0; for (int i = 0; i < scores.Length; i++) { sumSta += courses[i].couCredit * scorePoint[i]; sumOrd += scores[i] * courses[i].couCredit; sumCre += courses[i].couCredit; } ordGPA = sumSta * 1.0 / sumCre; staGPA = sumOrd * 4.0 / (sumCre * 100); } public void disStudent() { //要先呼叫calGPA()來計算GPA calGPA(); Console.WriteLine("學號:{0}\t姓名:{1}", stuNumber, stuName); Console.WriteLine("\t課程名\t學分\t分數"); for (int i = 0; i < courses.Length; i++) Console.WriteLine("\t{0}\t{1}\t{2}", courses[i].couName, courses[i].couCredit, scores[i]); Console.WriteLine("常見演算法GPA={0:n},標準演算法GPA={1:n}", ordGPA, staGPA); } } //Course類包含課程名稱和對應的學分 class Course { public string couName; public int couCredit; public Course() { } public Course(string name, int credit) { couCredit = credit; couName = name; } } static void Main(string[] args) { Student student = new Student("王華", "1"); Course[] courses = new Course[] { new Course("課程1", 4), new Course("課程2", 3), new Course("課程3", 2), new Course("課程4", 6), new Course("課程5", 3) }; int[] scores = new int[] { 92, 80, 98, 70, 89 }; student.setScore(scores); student.setCourse(courses); student.disStudent(); } } }

注意物件引用使用前要進行例項化