问题
I have a program that uses a formula to calculate the refurb on a unit (parts replaced on cableboxes that were damaged) divided by total units (cableboxes that went through refurb, but did not have any parts replaced). I looked up casting online, and the format for it is:
int valuetoconvert = Convert.ToInt32;
I'm doing that, but I still get the following error:
Cannot implicitly convert type 'double to int. An explicit conversion exists(are you missing a cast?)
What am I doing wrong? Can someone please help? Thank you.
Here's some of my code:
private int GetRefurbRate()
{
string sql = "";
double Refurb_Rate;
int totalRefurb = 0;
int totalUnits = 0;
string error_msg = "";
sql = "SELECT COUNT(rp.repair_ord) " +
"FROM " + schema + ".repair_part rp " +
"WHERE rp.repair_ord = '" + repair_ord + "' ";
while (true)
{
if (!myDb.RunSql(sql, true))
{
error_msg = "DBError for getting Refurb Rate";
break;
}
if (myDb.dbRdr.HasRows)
{
if (myDb.dbRdr.Read())
{
try //Try and Catch are here b/c I originally had everything ints, and and they just caught the 0 exception.
{
Refurb_Rate = Convert.ToInt32( totalRefurb / totalUnits * 100); //This is where I try to perform the cast.
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
//int Refurb_Rate = Convert.ToInt32(Refurb_Rate);
}
break;
}
myDb.dbRdr.Close();
if (error_msg != String.Empty)
{
MessageBox.Show(error_msg, "Get Refurb Rate",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
回答1:
You say you want an int cast, but you actually need to cast to a double. You can do that like so (Example Code):
Refurb_Rate = (double)totalRefurb / (double)totalUnits * 100d;
Otherwise, you need to change Refurb_Rate
from a double
to an int
.
回答2:
You need to say that you want an int cast:
double a;
int b = (int) a;
回答3:
I don't understand your error, because Refurb_Rate
is a double and everything else is an int. However, I think what you really want is this:
if (totalUnits != 0)
Refurb_Rate = totalRefurb * 100.0 / totalUnits;
Or possibly you want something like this:
int Refurb_Rate = 0;
...
if (totalUnits != 0)
Refurb_Rate = totalRefurb * 100 / totalUnits;
回答4:
Try this:
Refurb_Rate = (int)((double)totalRefurb / totalUnits * 100);
Make sure you case the int to double otherwise 1 / 2 will equal zero instead of .5
来源:https://stackoverflow.com/questions/5625038/how-do-i-cast-a-double-to-an-int