Bra*_*olf 0 c# type-conversion
我一直收到这个错误:
"无法隐式地将类型'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();
Run Code Online (Sandbox Code Playgroud)
这是新代码:
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();
Run Code Online (Sandbox Code Playgroud)
但我仍然得到一个转换错误,从double到long,long到int ...
Pie*_*ult 12
我想你的意思是在y这里使用你的变量而不是x:
PZ = ((10-(PZ + ISBN * y) % 10) % 10);
Run Code Online (Sandbox Code Playgroud)
作为一个侧面说明,你会在这两个获得编译错误PZ并且i,你需要在使用前初始化它们的值,例如int PZ = 0;和int i = 0;
请使用有意义的名字; PZ,i,x并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();
Run Code Online (Sandbox Code Playgroud)
以下是更改:
- 您可以直接在for循环中声明我,它会为您节省一条线.
- 不要将ISBN放入长文本中,而是将其保存在字符串中.只需逐个迭代每个字符.
- 每个数字都可以通过取ASCII值获得,并删除0的值.
- % 2 == 1事情基本上是"如果数字在奇数位置",你可以应用*3.这取代了你Math.Pow不太清楚的.
| 归档时间: |
|
| 查看次数: |
272 次 |
| 最近记录: |