我自己学习C#,正在解决项目Euler问题.我编写了下面的代码来解决问题8,它要求在一个长数字序列中找到13个连续数字的最大乘积.我从文件中读取了这个数字序列到程序中.
首先,我首先将数值变量"maxProduct"和"productTmp"定义为类型为"int",但我没有得到正确答案,因为它大于此类型的最大范围.令我困惑的是,我没有收到错误或警告,说我在处理我的注册时试图操纵太大的数字.相反,它似乎"包围"它的范围,这看起来毫无用处.这是怎么回事?
其次,它在哪里读取文件是我在网上找到的.但是,出于某种原因,我不能只编写"IO.StreamReader",但我必须包含"System".在它面前,即使我已经包含了"使用系统"; 线.我认为using语句使得"System"中包含的所有内容都可以在没有System.-prefix的情况下进行参考.
第三,在它读取文件的while循环中,发生了什么?我的猜测是(line = file.ReadLine())是一个布尔语句,但在这种情况下,它可以等于null是没有意义的.另外,我没有给"line"一个值,所以该语句看起来像是将line的null值与其他值进行比较.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace problem8
{
class Program
{
static void Main(string[] args)
{
int noAdjacentDigits = 13;
long maxProduct = 0;
string numberSequence = "", line;
System.IO.StreamReader file = new System.IO.StreamReader("C:/problem8.txt");
while ((line = file.ReadLine()) != null)
{
numberSequence = numberSequence + line;
}
for (int i = 0; i <= numberSequence.Length-noAdjacentDigits;i++)
{
string substrTmp = numberSequence.Substring(i, noAdjacentDigits);
long productTmp = 1;
for (int j = 0; j <= noAdjacentDigits-1; j++)
{
productTmp = productTmp * int.Parse(substrTmp.Substring(j,1));
}
if (productTmp > maxProduct) maxProduct = productTmp;
}
Console.WriteLine(maxProduct);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
相反,它似乎"包围"它的范围,这看起来毫无用处.这是怎么回事?
是的,除非您将数学放在一个checked块中或使用/checked编译器选项.该决定主要是出于性能原因,因为溢出检查需要时间并且通常不是必需的.
我不能写
IO.StreamReader,但我必须包括System.在它面前
您无法在命名空间的中间启动声明.添加Using System.IO到顶部,您只需键入StreamReader.
我的猜测是(line = file.ReadLine())是一个布尔语句
不,ReadLine返回一个字符串,即null如果已到达文件末尾.
该文档是相当明确的:
从当前流中读取一行字符并将数据作为字符串返回.
...
返回值
null是否到达输入流的末尾.
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |