我正在编写一个计算gpa的程序。唯一不起作用的是当我尝试编写代码以防止gpa超过4或低于0.这是我的全班。我认为问题可能出在我的gpa全部财产中。在我的程序类中,我调用函数,我有代码要求studentID,firstName,lastName和gpa。当我运行程序并输入5的gpa时,它仍然返回数字5,字母等级为A.我需要它返回一个字母等级为A的数字4.任何帮助将不胜感激。
using System;
using System.Collections.Generic;
using System.Text;
namespace UnitTest1
{
public class Student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public double Gpa { get; set; }
private string letterGrade;
public string LetterGrade
{
get
{
if (GPA >= 0 && GPA <= 0.99)
{
return "F";
}
else if (GPA >= 1 && GPA <= 1.29)
{
return "D";
}
else if (GPA >= 1.3 && GPA <= 1.69)
{
return "D+";
}
else if (GPA >= 1.7 && GPA <= 1.99)
{
return "C-";
}
else if (GPA >= 2 && GPA <= 2.29)
{
return "C";
}
else if (GPA >= 2.3 && GPA <= 2.69)
{
return "C+";
}
else if (GPA >= 2.7 && GPA <= 2.99)
{
return "B-";
}
else if (GPA >= 3 && GPA <= 3.29)
{
return "B";
}
else if (GPA >= 3.3 && GPA <= 3.69)
{
return "B+";
}
else if (GPA >= 3.7 && GPA <= 3.99)
{
return "A-";
}
else if (GPA == 4)
{
return "A";
}
return LetterGrade;
}
//All of this code sets the gpa number to a letter grade
}
private double gPA;
public double GPA
{
get
{
if (Gpa <= 0)
{
return 0;
}
else if (Gpa >= 4)
{
return 4;
}
else
{
return Gpa;
}
}
set
{
if (Gpa <= 0)
{
Gpa = 0;
}
else if (Gpa >= 4)
{
Gpa = 4;
}
Gpa = value; // <<=== remove me please
}
}
public Student(int studentID, string firstName, string lastName, double gpa)
{
StudentID = studentID;
FirstName = firstName;
LastName = lastName;
Gpa = gpa;
}
public void PrintTranscript()
{
Console.WriteLine("");
Console.WriteLine("{0, -20} {1, 26}", "University of Coding", $"Student ID: {StudentID}");
Console.WriteLine("{0, -20} {1, 23}", "123 Sea Sharp Street", "Date: 02/15/2018");
//The coordinates in these two lines sets the text in a certain spot in the output screen
Console.WriteLine("Cedarville, OH 45314");
Console.WriteLine($"Student: {FirstName} {LastName}");
Console.WriteLine("");
Console.WriteLine($"Current GPA {Gpa}");
Console.WriteLine("");
Console.WriteLine($"Letter Grade: {LetterGrade}");
//This code outputs what the user input
}
}
}
答案 0 :(得分:1)
你可以摆脱Gpa
属性(你已经有一个支持字段,并且正在使用自定义的get和set方法),你的getter和setter可以简化:
private decimal gPA;
public decimal GPA
{
get
{
return gPA;
}
set
{
if (value <= 0) // use value, not gPA here
{
gPA = 0;
}
else if (value >= 4)
{
gPA = 4;
}
else
{
gPA = value;
}
}
}
如果您想使用完全相等的比较,我也会切换到decimal
,如果您想要的话,我会使用<
代替<=
(例如{ {1}}比< 4
)
答案 1 :(得分:0)
我认为你根本不需要一个二传手,你输出了错误的属性。
public double GPA
{
get
{
if (Gpa <= 0)
{
return 0;
}
else if (Gpa >= 4)
{
return 4;
}
else
{
return Gpa;
}
}
}
Console.WriteLine($"Current GPA {GPA}");