简体   繁体   中英

C# - What's wrong with my conversion from double to int?

I keep getting this error:

"Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)"

Code:

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

Here is the new code:

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

But I'm still getting a conversion error for double to long and long to int...

I think you meant to use your y variable here instead of x :

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

As a side note, you'll get compilation errors on both PZ and i , you need to initialize their values before using them, eg int PZ = 0; and int i = 0;

And please, use meaningful names; PZ , i , x and y don't mean anything to someone reading your code, or even to you in a few weeks.


Okay, I've modified it a little...

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

Here's the changes :
- You can declare i directly in your for loop, it'll save you a line.
- Instead of putting the ISBN into a long, keep in in a string. Just iterate over each character one by one.
- Each digit can be obtained by taking the ASCII value, and removing the value of 0.
- The % 2 == 1 thing is basically "If the number is at an odd position", where you can apply the *3. This replaces your Math.Pow that wasn't very clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM