how to get output of a variable as float value

核能气质少年 提交于 2019-12-24 19:06:00

问题


i m having the follwing problem.. want to get the result in float

suppose

int a= convert.toint32(textbox1.text);
int b= convert.toint32(textbox2.text);

float ans= math.sqrt(a*b);
label1.text= ans.tostring();

output..

a=7
b=3

ans should be= 4.582 but i get an error

cannot implicitly convert type 'double' to 'float'.

pls help..how can i get the float ans...


回答1:


Change your code to

double ans = math.sqrt(a*b);



回答2:


double is just a larger float. Math.Sqrt() returns a double, not a float. You can fit more numbers in a double than the float type can accurately represent, and so in your code the compiler can't promise that an automatic conversion won't not lose important data, hence the exception.

To get around this, you have two options:

  1. explicit cast: float ans = (float)Math.Sqrt(a*b);
  2. use a double: double ans = Math.Sqrt(a*b);

Of the two, I recommend the latter.

As a side note, the reverse conversion is okay because double can always accurately represent anything you might find in a float variable. For example, this is perfect okay from the type system's point of view:

float divide(int a, int b) { return a/(float)b;}
double ans = divide(5,2);



回答3:


Math.sqrts return value is double. So, you have two options.

  1. Convert the returned double to a float as so: float ans = (float)Math.sqrt(a * b);
  2. Change the type of ans to double: double ans = Math.sqrt(a * b);

Option 2 would, in most cases, be your best option unless you specifically need a float, because double is a higher precision value.




回答4:


You could just cast directly to a float.

 float ans = (float)Math.Sqrt( a * b );



回答5:


You need to explicitly cast the result as double has a greater range of values than a float (16 digits to 7):

  float ans= (float)Math.Sqrt(a*b);

But unless you have a reason you haven't told us about then just use a double.




回答6:


float ans= math.sqrt(a*b); 

should be

float ans= (float)Math.Sqrt(a*b); 

You need to explicitly cast to float because this conversion results in loss of information so the compiler will not automatically cast for you. That way the compiler ensures that the lossy conversion is intentional.




回答7:


Math.Sqrt method returns a value of type double.

But you're trying to put this value to float type. But double doesn't have an implicit conversion to float. So the alternatives:

  • declare an answer as double: double ans = Math.Sqrt(a*b)

  • or explicitly convert result to float type: (float)Math.Sqrt(a*b).



来源:https://stackoverflow.com/questions/2868575/how-to-get-output-of-a-variable-as-float-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!