2015-09-22 36 views
-1

因此,這是問題.......乘以來自用戶的輸入將在C#

上下文代碼:

你淋浴的時間越長,你可以使用更多的水。但是多少?即使你有一個「低流量」噴頭,你的噴頭每分鐘可以吐出1.5加侖的水。一加侖是128盎司,所以淋浴吐出每分鐘1.5×128 = 192盎司的水。一瓶典型的水可能是16盎司。因此,進行1分鐘的淋浴就類似於使用192÷16 = 12瓶水。進行10分鐘的淋浴就像使用120瓶水。這些數字有助於瞭解淋浴中用水的數量! 在〜/ workspace/pset1目錄下的一個名爲water.c的文件中寫入一個程序,該程序在幾分鐘內提示用戶輸入其淋浴的長度(作爲正整數),然後打印相當數量的每個樣本輸出的水(作爲一個整數),其中帶下劃線的文本代表一些用戶的輸入。

用戶名@ ide50:〜/工作區/ PSET1 $ ./water 分鐘:10個 瓶:120 爲簡單起見,可以假設用戶將輸入一個正整數,因此無需用於錯誤校驗(或任何循環)這次!而且不必擔心溢出!

我當前的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace console_water 
{ 
    class water_amount 
    { 
     static void Main(string[] args) 
     { 
      /*variable decleration*/ 
      int multiply, divide; 
      int userInput = Console.Read(); 
      multiply = 192; 
      divide = 16; 

      /*getting user input*/ 
      Console.WriteLine("Length of shower in minutes:"); 

      Console.Read(); 

      userInput = multiply/divide; 

      Console.WriteLine("The amount of water used is:" + userInput); 
     } 
    } 
} 

但它不工作。

+1

另一個問題使用'Console.Read()'不正確。 – crashmstr

+5

很酷。什麼不工作,但?你到底在想什麼?認真思考一下在這裏幫助你的人。我們不會閱讀頭腦或類似的東西。給我們儘可能多的信息,但沒有更多(這是什麼大規模的介紹?)。 – async

+0

這是非常錯誤的。在提示用戶之前,你得到一個*字符代碼*,然後得到另一個被丟棄的*字符代碼,然後你只用整數除以兩個整數。 – crashmstr

回答

2

嘗試:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace console_water 
{ 
    class water_amount 
    { 
     static void Main(string[] args) 
     { 
      /*variable decleration*/ 
      int multiply, divide; 
      int userInput; 
      multiply = 192; 
      divide = 16; 

      /*getting user input*/ 
      Console.WriteLine("Length of shower in minutes:"); 

      userInput = int.Parse(Console.ReadLine()); 

      int numBottlesMinute = multiply/divide; 

      Console.WriteLine("The amount of water used is:" + userInput * numBottlesMinute); 
     } 
    } 
} 

userInput = int.Parse(Console.ReadLine());這個讀你的淋浴長度

int numBottlesMinute = multiply/divide;你應該讓你在一個變量每升用瓶的數量(更好不變......但確定你的例子)

Console.WriteLine("The amount of water used is:" + userInput * numBottlesMinute);只需打印結果,每分鐘瓶數*淋浴長度。

+0

非常感謝你的幫助,我認爲它現在正在工作。併爲這樣的問題格式表示歉意。我只有最後一個問題,是否有任何方法來保持控制檯打開將在最終的工作添加一個Console.ReadKey? –

+0

正如你所說,只要在最後寫上Console.ReadKey()即可。如果這有助於您解決問題,請將其標記爲答案。 – blfuentes

1

您沒有正確使用Console.ReadConsole.Read不會在用戶輸入控制檯時自動存儲用戶輸入 - 如果要使用它,則必須明確捕獲並存儲它。

如果我是你,我會使用Console.ReadLine(),它會將所有用戶的輸入提升到按下回車鍵。

要獲得multiply值,你可以這樣做:

Console.WriteLine("Minutes: "); 
int input = int.Parse(Console.ReadLine()); 

請注意,你需要做的對用戶的輸入int.Parse,作爲Console.ReadLine()回報string