【问题标题】:C# - What's wrong with my conversion from double to int?C# - 我从 double 到 int 的转换有什么问题?
【发布时间】:2013-11-15 07:55:54
【问题描述】:

我不断收到此错误:

"不能将类型'double'隐式转换为'int'。一个显式的 存在转换(您是否缺少演员表?)”

代码:

Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
int ISBN = Convert.ToInt32(ISBNstring);
int PZ;
int i;
double x = Math.Pow(3, (i + 1) % 2);
int y = (int)x;
for (i = 1; i <= 12; i++)
{
    PZ = ((10-(PZ + ISBN * x) % 10) % 10);
}
Console.WriteLine(PZ);
Console.ReadLine();

这是新代码:

 Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
long ISBN = Convert.ToInt32(ISBNstring);
long ISBN1 = (Int64)ISBN;
int PZ = 0;
int i;
for (i = 1; i <= 12; i++)
{
    double x = Math.Pow(3, (i + 1) % 2);
    long y = (double)x;
    PZ = ((10 - (PZ + ISBN * y) % 10) % 10);
}
Console.WriteLine(PZ);
Console.ReadLine();

但我仍然收到 double 到 long 和 long 到 int 的转换错误...

【问题讨论】:

    标签: c# type-conversion


    【解决方案1】:

    我认为您的意思是在这里使用您的 y 变量而不是 x

    PZ = ((10-(PZ + ISBN * y) % 10) % 10);
    

    附带说明一下,PZi 都会出现编译错误,您需要在使用它们之前初始化它们的值,例如int PZ = 0;int i = 0;

    请使用有意义的名称; PZixy 对阅读您的代码的人没有任何意义,甚至对几周后的您也没有任何意义。


    好的,我稍微修改了一下...

    Console.WriteLine("ISBN-Prüfziffer berechnen");
    Console.WriteLine("=========================");
    Console.WriteLine();
    Console.Write("ISBN-Nummer ohne Prüfziffer: ");
    string ISBNstring = Console.ReadLine();
    
    int sum = 0;
    for (int i = 0; i < 12; i++)
    {
        int digit = ISBNstring[i] - '0';
        if (i % 2 == 1)
        {
            digit *= 3;
        }
        sum += digit;
    }
    int result = 10 - (sum%10);
    
    Console.WriteLine(result);
    Console.ReadLine();
    

    以下是更改:
    - 你可以直接在你的 for 循环中声明 i,它会为你节省一行。
    - 不要将 ISBN 放入一个长字符串中,而是放入一个字符串中。只需逐个迭代每个字符。
    - 取ASCII值,去掉0的值即可得到每一位数字。
    - % 2 == 1 基本上是“如果数字在奇数位置”,您可以在其中应用 *3。这取代了您不太清楚的Math.Pow

    【讨论】:

    • 发现,删除了我的答案
    • @Bradoff,只是对答案的一个小补充。看起来 x(和 y 分别)的计算应该发生在循环中,或者?
    • 谢谢!现在错误消失了。但是由于某种原因,代码并没有像我想象的那样工作。
    • @Bradoff,看看我上面的评论。这也许就是它没有按预期工作的原因......
    • @Bradolf 那是因为 int 最大值是 2 147 483 647。使用 long 代替存储 12 位数字
    猜你喜欢
    • 2013-05-31
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 2013-08-26
    • 2014-12-12
    相关资源
    最近更新 更多