2016-10-13 4 views
0

私はちょうどコーディングを学び始めました、約1週間それに行ってきました。私は+と - を行う電卓を作ってみたかったのですが、使用したいものをユーザーに選択させる方法を理解することはできません。ここにコードは です。 xがyよりも大きい場合 - X iがyよりも低く、かつどうかを見ることができるように私の最初の計算機で助けを必要とする

 int x; 
     int y; 
     Console.WriteLine("Welcome to my calculator program!"); 
     Console.WriteLine("This calculator for now can only do + and -"); 
     Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +"); 

     Console.WriteLine("pls write in you x"); 
     x = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("pls write in your y"); 
     y = Convert.ToInt32(Console.ReadLine()); 

     if (x > y) 
     { 
      Console.WriteLine("you chose to use minus"); 
      int sum = x - y; 
      Console.WriteLine("result: {0}", sum); 
      Console.WriteLine("Press a key to exit"); 
      Console.ReadLine(); 
     } 
     else 
     { 
      Console.WriteLine("you chose to use plus"); 
      int sum1 = x + y; 
      Console.WriteLine("result: {0}", sum1); 
      Console.WriteLine("Press a key to exit"); 
      Console.ReadLine(); 
     } 


    } 
} 

} はわずか+用いられます。私はそれを動作させる方法を知っていた唯一の方法です。

+2

読む文字。スイッチケースを使用し、それに応じてタスクを実行してください。 –

+0

xとyを記述するようにユーザーに依頼してください。ユーザーに操作を書いてもらうか、4つの操作+、 - 、*、/のいずれかを探しているスイッチを持っていないか、Console.Log( "無効な操作")を書いてください。また、コンソールからxとyを取るときは、IntまたはDouble TryParseメソッドを使います。これにより、プログラムが現在の状態で例外をスローするため、ユーザーがe2e21aをnumberに書き込むことができなくなります。したがって、要約コンソールからの操作、TryParseメソッドの使用、エラーが発生した場合にメソッドの実行を終了する方法を参照してください(無効な操作またはコンソールからのint/decimalの無効)! – mybirthname

答えて

0

コンピュータプログラムの偉大な世界へようこそ。 アプリケーションの開発は、ユーザーにオプションを与え、その要求を動的に処理することに関するものです。 したがって、xとyの値を取得すると、ユーザーから演算子が取得される可能性があります。簡単な例は、次のようになります。

int x; 
int y; 
Console.WriteLine("Welcome to my calculator program!"); 
Console.WriteLine("This calculator for now can only do + and -"); 
Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +"); 

Console.WriteLine("pls write in you x"); 
x = Convert.ToInt32(Console.ReadLine()); 
Console.WriteLine("pls write in your y"); 
y = Convert.ToInt32(Console.ReadLine()); 
Console.WriteLine("insert operator"); 
string o = Console.ReadLine(); 

if (o=="-") 
{ 
    Console.WriteLine("you chose to use minus"); 
    int sum = x - y; 
    Console.WriteLine("result: {0}", sum); 
    Console.WriteLine("Press a key to exit"); 
    Console.ReadLine(); 
} 
else if (o=="+") 
{ 
    Console.WriteLine("you chose to use plus"); 
    int sum1 = x + y; 
    Console.WriteLine("result: {0}", sum1); 
    Console.WriteLine("Press a key to exit"); 
    Console.ReadLine(); 
} 
else 
{ 
    Console.WriteLine("the operator is not recognized"); 
} 

役に立つと分かったら答えをマークしてください。

0

まずはお試しいただきありがとうございます。今ではスニペットを改善するためにいくつかのメモを追加します。 int.TryParseを変換に使用してFormatExceptionsを処理し、ユーザーから操作者を取得し、スイッチケースを使用して識別し、ユーザー入力に従って操作を実行できます。

は、あなたが求めているものを達成するために、様々な可能な方法があります

int firstNumber, secondNumber; 
Console.WriteLine("pls write in you x"); 
if (!int.TryParse(Console.ReadLine(), out firstNumber)) 
{ 
    Console.WriteLine("Sorry this is not an integer, 0 will be assigned"); 
} 
Console.WriteLine("pls write in your y"); 
if (!int.TryParse(Console.ReadLine(), out secondNumber)) 
{ 
    Console.WriteLine("Sorry this is not an integer, 0 will be assigned"); 
} 

/Now you have two numbers to perform the operation 
// You can now prompt the user to enter the operator 
Console.WriteLine("pls enter the operator"); 
char operatorSign = Console.ReadKey().KeyChar; 
switch (operatorSign) 
{ 
    case '+' : 
     Console.WriteLine("Result {0} + {1} = {2}", firstNumber, secondNumber, firstNumber + secondNumber); 
     break; 
    case '_': 
     Console.WriteLine("Result {0} - {1} = {2}", firstNumber, secondNumber, firstNumber - secondNumber); 
     break; 
    case '*': 
     Console.WriteLine("Result {0} * {1} = {2}", firstNumber, secondNumber, firstNumber * secondNumber); 
     break; 
    default:    
     Console.WriteLine("Sorry we are not providing this operation"); 
     break; 
} 
Console.ReadKey(); 
1

をコピーして貼り付けられませんが、参考としてこのコードを考えてみましょう。操作に対応するため、オペレータの入力を求めているの最も簡単な:ここで

は同じのためのコードです:

using System.IO; 
using System; 

class Program 
{ 
    static void Main() 
    { 
     int x; 
     int y; 


     Console.WriteLine("Welcome to my calculator program!"); 
     Console.WriteLine("This calculator for now can only do + and -"); 

     // Reads x and y from console. 
     Console.WriteLine("Enter x :"); 
     x = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("Enter y :"); 
     y = Convert.ToInt32(Console.ReadLine()); 

     Console.WriteLine("Enter operator for corresponding operation on x and y.\nSupported operations x - y and x + y"); 
     string inputOpr = Console.ReadLine(); // Stores operation to perform 

     // Compares input operator to perform operation. 
     if (inputOpr == "-"){ 
      Console.WriteLine("you chose to use minus"); 
      int result = x - y; 
      Console.WriteLine("Result: {0}", result); 
      Console.WriteLine("Press a key to exit"); 
      Console.ReadLine(); 
     } 

     else if (inputOpr == "+"){ 
      Console.WriteLine("you chose to use plus"); 
      int result = x + y; 
      Console.WriteLine("Result: {0}", result); 
      Console.WriteLine("Press a key to exit"); 
      Console.ReadLine(); 
     } 
     else{ 
      Console.WriteLine("Invalid Input"); 
     } 
    } 
} 
0

あなたはこの

static void Main(string[] args) 
    { 
     int x; 
     int y; 
     Console.WriteLine("Welcome to my calculator program!"); 
     Console.WriteLine("This calculator for now can only do + and -"); 
     Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +"); 

     Console.WriteLine("pls write in you x"); 
     x = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("pls write in your y"); 
     y = Convert.ToInt32(Console.ReadLine()); 

     string opt; 
     int res; 
     do 
     { 
      Console.Write("Enter your operator [+/-/:/x]:\t"); 
      opt= Console.ReadLine(); 
      res = "/+/-/:/x/".IndexOf("/" + opt + "/"); 

     } while (res == -1); 

     double result; 
     switch (opt) 
     { 
      case "+": 
       result= x + y; 
       break; 
      case "-": 
       result = x - y; 
       break; 
      case ":": 
       result = (double)x/(double)y; 
       break; 
      case "x": 
       result = x*y; 
       break; 

      default: 
       result = -9999; 
       break; 
     } 
     Console.WriteLine("\n{0} {1} {2} = {3}", x, opt, y, result); 
     Console.ReadLine(); 

    } 

} 
1

のような単純なアプローチを行くことができる(ユーザーに尋ねます)答えられました。しかし、おそらく実際に達成したいのは、ユーザが2+3のような文字列を入力し、プログラムが単に答えを出す本格的な電卓を書くことです。あなたはインタプリタを書くことを切望しています。

  • ユーザー入力をスキャンし、一連のトークンにそれを翻訳:あなたはそれについて考える場合

    、次の3つのタスクを実行する必要があります。これは、「プラス演算子」値2を有する整数 'トークン直列に文字列「2 + 3」に変換された「値を持つ整数を3」は、

  • 結果を

以上を計算するためにトークンを解釈します(例えば、あなたが言ったように、+と - だけが始めることを許していれば)、コードはより簡単になります(あなたが設定した規則に従って入力が解釈できないならば失敗します)。

もっと深く掘り下げたい場合は、このトピックで多数のリソースを利用できます。私はthis series of blog postsという読書を楽しんでいます(著者はPythonを使用しますが、原則は同じです)。

最後に、あなたがしようとしていることの多くがすでに達成されていることがわかります。すでに数式を解析して評価するライブラリがあります(例:NCalcMathos)。最後のノートで

は、Roslynのは、あなたが簡単に任意のC#の式を解析することができますので、また、このように、簡単な計算機を構築するために使用することができます:コンソールからも

class Program 
{ 
    static void Main(string[] args) 
    { 
     CSharpReplAsync().Wait(); 

    } 

    private static async Task CSharpReplAsync() 
    { 
     Console.WriteLine("C# Math REPL"); 
     Console.WriteLine("You can use any method from System.Math"); 

     var options = ScriptOptions.Default 
      .AddImports("System", "System.Console", "System.Math"); 

     var state = await CSharpScript.RunAsync("WriteLine(\"Hello from Roslyn\")", options); 

     while (true) 
     { 
      Console.Write("> "); 
      string expression = Console.ReadLine(); 
      if (string.IsNullOrEmpty(expression)) 
       break; 
      try 
      { 
       state = await state.ContinueWithAsync(expression, options); 
       if (state.ReturnValue != null) 
        Console.WriteLine(state.ReturnValue); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.Message); 
      } 
     } 
    } 
} 
関連する問題