Abd*_*mid 9 .net c# comparison
我正在尝试提出一个程序来计算用户输入的分数.我也试图设置用户输入的高低的限制(即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 <First Last>: ");
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 <Example: 100.0>: ");
Exam_1 = Convert.ToDecimal(Console.ReadLine());
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 <Example: 95.0>:");
Exam_1 = Convert.ToDecimal(Console.ReadLine());
Console.Write("Please enter score for Exam 2 <Example: 0.0>: ");
Exam_2 = Convert.ToDecimal(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)
Ian*_*Ian 17
我在代码中注意到至少有四个问题.
首先,如上所述,您应该使用M
后缀告诉C#编译器它是一个decimal
用于接受的比较:
if (Exam_1 < 0.0M | Exam_1 > 100.0M)
Run Code Online (Sandbox Code Playgroud)
但其次,使用||
而不是|
,因为你想做OR
操作,而不是Bitwise-OR
if (Exam_1 < 0.0M || Exam_1 > 100.0M) //change | to ||
Run Code Online (Sandbox Code Playgroud)
而第三,我觉得很重要的是你知道这一点:你就不需要 decimal
为考试标记数据类型(除非你的考试标记可以格式99.12345678901234556789012345的-这是完全不可能的).
decimal
通常用于需要非常高精度的数字(例如money
在库中计算),精度高达16位以上.如果您的考试成绩不需要,请不要使用decimal
,这是过度的.只需使用double
或int
或float
为你Exams
,你很可能在正确的轨道上.
第四,关于你的错误处理,这是不正确的做法:
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 <Example: 95.0>:");
Exam_1 = Convert.ToDecimal(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)
由于两个原因:
Exam_1
在街区之外(没有{}
支架)if
,而你应该使用while
这是正确的方法:
double Exam_1 = -1; //I use double to simplify
Console.Write("Please enter score for Exam 1 <Example: 100.0>: ");
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 <Example: 95.0>:");
Exam_1 = Convert.ToDouble(Console.ReadLine());
} //see the end curly bracket
Run Code Online (Sandbox Code Playgroud)
在C#语言中,缩写并不意味着作用域,与Python之类的语言不同.
归档时间: |
|
查看次数: |
7450 次 |
最近记录: |