0

このエラーが発生し続けます:

「タイプ '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 への変換エラーがまだ発生しています...

4

1 に答える 1

12

y代わりにここで変数を使用するつもりだったと思いますx

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

補足として、 と の両方PZでコンパイル エラーが発生します。i使用する前に値を初期化する必要がありますint PZ = 0;int i = 0;

そして、意味のある名前を使用してください。PZixおよびyあなたのコードを読んでいる人にとっては何の意味もありません。


よし、ちょっと改造した…

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 を直接宣言できるため、1 行節約できます。
- ISBN を long にする代わりに、string に入れます。各文字を 1 つずつ繰り返します。
- 各桁は、ASCII 値を取り、0 の値を削除することによって取得できます。
-% 2 == 1基本的には、「数字が奇数の位置にある場合」であり、*3 を適用できます。Math.Powこれは、あまり明確ではなかったことを置き換えます。

于 2013-11-15T07:57:47.000 に答える