why does my float variable statement keeps on givi

2019-09-01 16:44发布

For some reason I keep getting an error saying 'Cannot implicitly convert type double to float' All over my code. I bolded and left a comment exactly where in my code I'm getting the errors. I cant seem to figure out what the problem is. I switched the data types all to 'double' instead of 'float' and the program ran smoothly with no errors. Can some one please tell me what I am doing wrong or what is missing from the code? (Edit: Bold does not seem to work on my code on this site).

2条回答
唯我独甜
2楼-- · 2019-09-01 16:51

The problem is that when you perform your multiplication (or other arithmetic operation) you are working with a literal such as 0.15. This value by default will be treated as a double by the compiler and so when multiplied against a float it results in the larger double result. To get around this you need to mark the literals as .15f so that they are treated as float literals.

查看更多
乱世女痞
3楼-- · 2019-09-01 16:53

In addition to Phil's suggestion you should use float.TryParse instead of float.Parse otherwise you might get FormatException if user enters invlaid text

float value;
if (float.TryParse(text, out value))
{
 // Parse success..
}
else
{
 // Parse failed...
}
查看更多
登录 后发表回答