【问题标题】:How do I cast a double to an int?如何将 double 转换为 int?
【发布时间】:2011-04-11 17:23:26
【问题描述】:

我有一个程序,该程序使用公式计算单元的翻新(更换损坏的电缆盒上的零件)除以总单元(经过翻新但没有更换任何零件的电缆盒)。我在网上查了一下casting,格式是:

int valuetoconvert = Convert.ToInt32;

我正在这样做,但我仍然收到以下错误:

无法将类型 'double 隐式转换为 int。存在显式转换(您是否缺少演员表?)

我做错了什么?有人可以帮忙吗?谢谢。

这是我的一些代码:

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);
}

【问题讨论】:

  • Refurb_Rate = Convert.ToInt32(totalRefurb / totalUnits * 100d);
  • (没有 C# 经验,只有 C,所以只是评论)在 C 中,如果你在变量之前写 (int),它会将逗号后面的内容删除。如果要四舍五入,请使用 ceil() 和 floor() 或 round() 等函数

标签: c# types casting double int


【解决方案1】:

你说你想要一个 int 转换,但你实际上需要转换为一个 double。你可以这样做(Example Code):

Refurb_Rate = (double)totalRefurb / (double)totalUnits * 100d;

否则,您需要将 Refurb_Ratedouble 更改为 int

【讨论】:

  • @FreeAslinBeer 我尝试了所有三种方法,但它仍然给我无法转换为 int 错误。它突出显示返回 Refurb_Rate。我应该更改我的返回类型吗?
【解决方案2】:

你需要说你想要一个 int 强制转换:

double a;
int b = (int) a;

【讨论】:

    【解决方案3】:

    我不明白你的错误,因为Refurb_Rate 是一个双精度值,而其他所有值都是一个整数值。但是,我认为您真正想要的是:

    if (totalUnits != 0)
        Refurb_Rate = totalRefurb * 100.0 / totalUnits;
    

    或者你可能想要这样的东西:

    int Refurb_Rate = 0;
    ...
    if (totalUnits != 0)
        Refurb_Rate = totalRefurb * 100 / totalUnits;
    

    【讨论】:

      【解决方案4】:

      试试这个:

      Refurb_Rate = (int)((double)totalRefurb / totalUnits * 100);

      确保将 int 大小写为 double,否则 1 / 2 将等于 0 而不是 .5

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-16
        • 2011-05-10
        • 1970-01-01
        • 2011-11-10
        • 2013-06-02
        • 1970-01-01
        • 2014-01-14
        相关资源
        最近更新 更多