【发布时间】:2014-01-12 15:23:20
【问题描述】:
所以第 59 行有我只能描述为 wackadoodle 错误(如果我正确理解我的代码的话),也就是说,如果你用Console.ReadLine() 离开返回行,文件将运行,如果你改变到Console.Read()),文件运行时会产生错误。奇怪的是它不应该运行,因为我不调用函数或执行实际的 console.writes 等。所以我希望有人可以帮助我理解这一点,或者确认我的想法是正确的我有一些古怪的代码,或者我对代码运行方式的理解不正确。
产生错误的代码:
public string GetStr(String StrVar)//note - using strings here
{
Console.Write(StrVar);return Console.ReadLine().ToLower().Trim();
}
如果return Console.ReadLine() 行更改为return Console.Read(),则文件错误 - 但文件应该真正运行,因为我实际上并没有调用任何东西 - 似乎字符串 vars 以某种方式自我写入控制台如果我明白发生了什么。
完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace a015_mealCalculator
{
class Program
{
public void Play()
{
//DisplayChek("DisplayChek!");
do //do while loop
{
DisplayStr(">>>-- Meal Calculator v1.3 --<<< \n\n\n");//Welcome
//ask info
String fName = GetStr("Enter your FIRST NAME here: ");
String lName = GetStr("Enter your LAST NAME here: ");
String rName = GetStr("Enter the NAME of the RESTURANT you are dinning at here: ");
String wholeName = fName + " " + lName;
double mealCost = GetDouble("How much was your meal " + fName + "?");
String mealGreeting = "\n" + wholeName + ", your meal at " + rName + " was:";
//process math
double tax = mealCost / 8;
double tip = mealCost % 18;
double totalCost = mealCost + tip + tax;
tax = Math.Round(tax, 2);//trim decimals
tip = Math.Round(tip, 2);//trim decimals
totalCost = Math.Round(totalCost, 2);
//Announce results
Console.WriteLine("\nMeal: " + mealCost);
Console.WriteLine(mealGreeting);
Console.WriteLine("Meal: $" + mealCost);
Console.WriteLine("Tax: $" + tax);
Console.WriteLine("Tip: $" + tip);
Console.WriteLine("Total: $" + totalCost);
} while (PlayAgain());
DisplayStr("Enjoy Your Meal!"); //Salutation
}
//MaxBox
public void DisplayChek(String StringNameIs)
{ Console.WriteLine("I am in " + StringNameIs); }//Where are we?
public void DisplayStr(String StrTxt)
{ Console.WriteLine(StrTxt); }
public void DisplayRs()
{ Console.Write("\n\n"); }
public string GetStr(String StrVar)//note - using strings here
{ Console.Write(StrVar);return Console.ReadLine().ToLower().Trim(); }
public double GetDouble(String doubleRequest)// We take in a STRING but we return a DOUBLE
{
Console.WriteLine(doubleRequest + ": "); // HERE we use the STRING to ask for the DOULBE
return double.Parse(Console.ReadLine()); //HERE we RETURN the DOUBLE asked for!
}
public Boolean PlayAgain()
{
Console.Write("\n\nDo you want to play again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
static void Main(string[] args)
{
Program MealCalculator = new Program();
MealCalculator.Play();
//Play keeps file open
//Console.Read();
}
}
}
【问题讨论】:
-
你在说什么文件?
-
我将所有代码发布到我上面提到的文件(命名空间 a015_mealCalculator)中,并发布了我所理解的产生超级古怪的单一方法/函数,我相信发生在第 59 行。
-
旁注:
double tip = mealCost % 18;不会按照你的意思行事。%不是百分比,而是模数。 -
请说明您在执行what时遇到的错误,而不是“古怪”。
-
“字符串变量以某种方式自我写入控制台”——不,它们不是。没有任何事情“以某种方式”自动发生。