由于某种原因,我无法理解程序的逻辑:
如果必须将leastNumber初始化为0,那么最小数字是否总是0? (我提供了一个基本的txt文件,其中包含各种整数的列表,这就是TwoNumbers.txt的内容)
string[] lines = File.ReadAllLines ( "TwoNumbers.txt" );
int leastNumber = 999;
int previousNumber = 0;
foreach (string line in lines)
{
int currentNumber = int.Parse ( line );
currentNumber = leastNumber;
if (currentNumber < previousNumber)
{
leastNumber = currentNumber;
}
}
Console.WriteLine ("The least number is: " + leastNumber);
Console.ReadLine ();
答案 0 :(得分:2)
试试这个:
string[] lines = File.ReadAllLines("TwoNumbers.txt");
int leastNumber = int.MaxValue;
foreach (string line in lines)
{
int currentNumber = int.Parse(line);
if (currentNumber < leastNumber)
{
leastNumber = currentNumber;
}
}
Console.WriteLine("The least number is: " + leastNumber);
Console.ReadLine();
答案 1 :(得分:2)
在你的程序中,你将覆盖当前的数字:
int currentNumber = int.Parse ( line );
currentNumber = leastNumber;
第二行将导致第一次迭代中的当前数字为999,这将导致在检查后将leastNumber设置为0。
在那之后,currentNumber将始终设置为0,并保持这种状态。
你根本不需要以前的号码。只是做:
string[] lines = File.ReadAllLines ( "TwoNumbers.txt" );
int leastNumber = int.MaxValue;
foreach (string line in lines)
{
int currentNumber = int.Parse ( line );
if (currentNumber < leastNumber)
{
leastNumber = currentNumber;
}
}
Console.WriteLine ("The least number is: " + leastNumber);
Console.ReadLine ();
答案 2 :(得分:0)
你的问题在比较中。
您正在比较currentNumber < previousNumber
,但previousNumber
始终等于0,因为您尚未为其指定任何内容。
答案 3 :(得分:0)
有NEGATIVE整数,小于0.是否有任何阻止负整数出现在你的文本文件中?
答案 4 :(得分:0)
呸。 我明白我做了什么。
string[] lines = File.ReadAllLines ( "TwoNumbers.txt" );
int leastNumber = 0;
int previousNumber = 0;
foreach (string line in lines)
{
int currentNumber = int.Parse ( line );
**currentNumber = leastNumber;**
if (leastNumber == 0 || currentNumber < leastNumber)
{
leastNumber = currentNumber;
}
previousNumber = currentNumber;
}
Console.WriteLine ("The least number is: " + leastNumber);
Console.ReadLine ();
不需要作业currentNumber = leastNumber;
答案 5 :(得分:0)
如果您认为字符串整数列表仅仅是因为您的测试方法(使用文本文件来保存您的测试数据)并将其提取到手头的问题,这似乎是找到了一个最低的整数值设置,您可以使用LINQ为您执行此操作:
int[] listOfPositiveInts = new int[]{2,3,4,5,1,67};
var minInt = listOfPositiveInts.Min();
Console.WriteLine(minInt);
如果您的业务问题是转换一个充满代表数字的字符串的文本文件,那么您应该更多地加强解决方案。
如果你想了解算法,那么你应该尝试用伪代码来思考
create variable to track current lowest number
initialize tracking Variable to the first number in my array
loop through the array of numbers to inspect
if the number I'm inspecting is lower than my current lowest number
replace my current lowest number with the number I'm inspecting
end loop
Display lowest value found
使用foreach循环时看起来像这样
// test data
int[] arrayOfNumbers= new int[]{2,3,4,5,1,67};
// search algorithm
int lowestValueFound = arrayOfNumbers[0];
foreach(int i in arrayOfNumbers)
{
if (i < lowestValueFound)
lowestValueFound = i;
}
Console.WriteLine("Lowest value found is {0}", lowestValueFound);
如果您试图理解算法,那么字符串转换可能只是噪音。如果您只是想完成它,请尝试使用整数数组并使用LINQ。