我尝试使用以下方法允许自己在我的控制台应用程序中输入极大值,例如10^15000
。此应用程序必须计算足够大的值,以便使用Stopwatch
对象进行计时,并在1秒内降落。到目前为止,我只能在使用Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
这是我的自定义ReadLine()方法:
static string ReadLine()
{
StringBuilder sb = new StringBuilder();
while(true){
char ch = Convert.ToChar(Console.Read());
sb.Append(ch);
if(ch == '\n'){
break;
}
}
return sb.ToString();
}
这是我的整个程序,专门用于算法时间测试:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using System.Diagnostics;
using System.IO;
namespace LabGrowthOfFunctions
{
class Program
{
static void Main(string[] args)
{
int userNum;
Console.Write("Please enter a number: ");
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
string tempString = ReadLine();
int.TryParse(tempString, out userNum);
Stopwatch sw = Stopwatch.StartNew();
//nsquaredgrowthversion1(userNum);
//ncubedfunction(userNum);
ntothefourthpowerfunction(userNum);
//nfunction(userNum);
//nlognfunction(userNum);
sw.Stop();
Console.WriteLine("Time used: {0} secs", sw.Elapsed.TotalMilliseconds / 1000);
Console.ReadLine();
}
private static void nsquaredgrowthversion1(int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum++;
}
private static void ncubedfunction(int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
sum++;
}
private static void ntothefourthpowerfunction(int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
for (int l = 0; l < n; l++)
sum++;
}
private static void nfunction(int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum++;
}
private static void nlognfunction(BigInteger n)
{
double sum = 0;
double result = 0.0;
result = Math.Log((double)n,2);
sum = (double)n * result;
}
//ReadLine recreated for large input sizes.
static string ReadLine()
{
StringBuilder sb = new StringBuilder();
while(true){
char ch = Convert.ToChar(Console.Read());
sb.Append(ch);
if(ch == '\n'){
break;
}
}
return sb.ToString();
}
}//end Main
}//end namespace LabGrowthOfFunctions
答案 0 :(得分:0)
您可以使用ReadKey()方法。读取输入的每个字符,附加到字符串,然后将字符串转换为Int。