Problem description: a conversion from the double type to the int type
Detailed Description: In the class, our web teacher used C # to relearn a small program for C Language Learning-a given score with a program to determine the level. C language students must know the switch... case... statement. The problem does not appear here, But before judging, We need to score mod 10, that is, we only want to judge the score level (excellent, good, medium, and pass) based on the "Ten" percentage score)
The error code is as follows:
Protected void btngrade_click (Object sender, eventargs E)
{
// Convert the text score to double
Double dgrade = convert. todouble (txtgrade. Text );
// Output on the webpage
Response. Write (dgrade );
Response. Write ("<br/>"); // line feed
// Double --> int
Int num = convert. toint16 (dgrade );
Response. Write (Num );
Response. Write ("<br/> ");
Num = num/10; // calculate ten digits
Switch (Num)
{
Case 10:
Case 9: Response. Write ("excellent"); break;
Case 8: Response. Write ("good"); break;
Case 7: Response. Write ("medium"); break;
Case 6: Response. Write ("pass"); break;
Default: Response. Write ("fail"); break;
}
}
The result is as follows:
Cause: int num = convert. toint16 (dgrade );
Convert. toint16 (), the function of this function is to convert the double type to the int type, this is no error, the error is wrong, this conversion method utilizes the idea of "Rounding.
The next step is to solve the problem.
Method (1 ):
The problem occurs in "Rounding". Exception: 59.5. After conversion 60. before conversion, we need to convert 59.5 to 0.5 to solve all the current problems. The main code is as follows:
I personally feel that this method is narrow, but for the question, if the children's shoes find this problem, please give me more advice.
Method (2 ):
Since we only want to get an integer of the double type, is there a function to retrieve the integer of the double type? The answer is yes. (What You Can't think of is what you can't do with code)
Method (3 ):
The final method is what the teacher thinks-forced type conversion
Summary: small problems often reflect the truth. Therefore, children's shoes should pay attention to the details and learn to summarize them. There is also a saying: "There is only one problem, and there are many ways to solve the problem ". In addition, if you want to pass by and find any errors, please kindly advise. Thank you.
C # type conversion problem 1