运算符'<'不能应用于'decimal'和'double'类型的操作数
我正在尝试提出一个程序来计算用户输入的分数。 我也试图设置用户输入的高低的限制(即0 = 100)。 但是当我使用十进制时,它一直给我这个错误,“运算符'<'不能应用于'decimal'和'double'类型的操作数”
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grade_Program { class Program { static void Main(string[] args) { string First; string Last; First = "Cristiano"; Last = " Ronaldo"; Console.Write("Please enter student name : "); Console.WriteLine(First + Last ); Console.WriteLine(" "); Console.WriteLine("*************NOTE**********************************************"); Console.WriteLine("*** Be sure to include decimal point for scores. ***"); Console.WriteLine("*** !!!All score should range from 0.00 to 100.00 !! ***"); Console.WriteLine("*** ***"); Console.WriteLine("*** For example : 80.50 ***"); Console.WriteLine("***************************************************************"); Console.WriteLine(" "); decimal Exam_1; decimal Exam_2; decimal Exam_3; decimal Assignment_1; decimal Assignment_2; Console.Write("Please enter score for Exam 1 : "); Exam_1 = Convert.ToDecimal(Console.ReadLine()); if (Exam_1 100.0) Console.Write("Exam score cannot be less than 0. or greater than 100.0. Please re-enter the score for Exam 1 :"); Exam_1 = Convert.ToDecimal(Console.ReadLine()); Console.Write("Please enter score for Exam 2 : "); Exam_2 = Convert.ToDecimal(Console.ReadLine());
我在代码中注意到至少有四个问题。
首先 ,如上所述,您应该使用M
后缀告诉C#编译器它是接受比较的decimal
:
if (Exam_1 < 0.0M | Exam_1 > 100.0M)
但其次 ,使用||
而不是|
,因为你想做OR
操作,而不是Bitwise-OR
if (Exam_1 < 0.0M || Exam_1 > 100.0M) //change | to ||
第三 ,我认为你知道这一点非常重要:你不需要 decimal
数据类型的考试标记(除非你的考试标记可以是格式99.12345678901234556789012345 – 这是非常不可能的)。
decimal
通常用于需要非常高精度的数字(例如银行中的money
计算),精度高达16位以上。 如果您的考试成绩不需要, 请不要使用decimal
,这是过度的 。 只需使用double
或int
或float
为您的Exams
,你很可能在正确的轨道上。
第四 ,关于你的error handling,这是不正确的做法:
if (Exam_1 < 0.0 | Exam_1 > 100.0) Console.Write("Exam score cannot be less than 0. or greater than 100.0. Please re-enter the score for Exam 1 :"); Exam_1 = Convert.ToDecimal(Console.ReadLine());
由于两个原因:
- 您的
Exam_1
在块之外(没有{}
括号) - 你在使用的同时使用
if
这是正确的方法:
double Exam_1 = -1; //I use double to simplify Console.Write("Please enter score for Exam 1 : "); Exam_1 = Convert.ToDouble(Console.ReadLine()); while (Exam_1 < 0.0 || Exam_1 > 100.0) { //see the curly bracket Console.Write("Exam score cannot be less than 0. or greater than 100.0. Please re-enter the score for Exam 1 :"); Exam_1 = Convert.ToDouble(Console.ReadLine()); } //see the end curly bracket
在C#语言中,缩写并不意味着作用域,不像Python这样的语言。
对于十进制,您必须在值中添加“M”后缀以告诉计算机它是小数。 否则计算机会将其视为双倍。
yourDecimal <98.56M;
正如其他人已经指出的那样。 要使用大于或小于运算符比较decimal
类型,必须将其与另一个decimal
类型进行比较。 为了将文字数字声明为十进制,它需要M
或m
后缀。 以下是decimal
类型的MSDN以供参考。
if (Exam_1 < 0.0m || Exam_1 > 100.0m)
这是修补程序的.NET小提琴。