文字列変数をdoubleに変換しようとしています。
これまで、Convert.ToDouble()を試しました。
string userAge;
Console.WriteLine("What is your age?");
Console.ReadLine();
Convert.ToDouble(userAge);
そして、それに対して操作を行おうとすると、userAge
このエラーが表示されます。
Program.cs(23,27): error CS0019: Operator '/' cannot be applied to operands of type 'string' and 'double' [/home/ccuser/workspace/csharp-working-with-numbers-arithmetic-operators-csharp/e3-workspace.csproj]
Program.cs(29,28): error CS0029: Cannot implicitly convert type 'string' to 'double' [/home/ccuser/workspace/csharp-working-with-numbers-arithmetic-operators-csharp/e3-workspace.csproj]
Program.cs(17,24): error CS0165: Use of unassigned local variable 'userAge' [/home/ccuser/workspace/csharp-working-with-numbers-arithmetic-operators-csharp/e3-workspace.csproj]
The build failed. Fix the build errors and run again.
助言がありますか?
Convert
呼び出しの結果を変数に割り当てるのではなく、単に破棄するだけです。Convertは、既存の変数の型を変更しません(他の考慮事項は別として、厳密に型指定された言語では変更できないため)。代わりに、数学で使用する新しい変数を生成します。
エラーは、関連するコードを見ずに推測userAge
します。これは、計算で使用しようとしたためです。これは、今説明したように、まだ文字列です。
また、ステップに戻るために、ReadLine操作の結果を最初にuserAge変数に実際に割り当てたことはありません。
この:
Console.WriteLine("What is your age?");
string userAge = Console.ReadLine();
double age = Convert.ToDouble(userAge);
もっと理にかなっているでしょう。そして、age
後で計算に使用します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加