The problem
Write a console-based application that displays every
integer value from 1 to 20, along with its squared value.
This is what I have done. All I am curious is if there another way to do it, other than while,do loops.
double max = 20;
double math, mathDouble;
for (double x = 1; x <= max; ++x)
{
math = x * 1;
mathDouble = math * math;
Console.WriteLine("The number is {0}, the square root of that number is {1}", math, mathDouble);
Loading
VulpesPosted Jan 5, 2012, 5:17 AM
1. Where possible, prefer integer to floating point arithmetic as it's faster and uses less memory.
2. You're actually calculating the square of the number here, not its square root.
In the days when processors performed addition more quickly than multiplication, this would have been a faster solution:
Jignesh TrivediPosted Jan 5, 2012, 1:19 AM
simply use,
double max = 20;
for (double x = 1; x <= max; ++x)
{
Console.WriteLine("The number is {0}, the square root of that number is {1}", x, x*x);
}
there is no use more variables. it also take up memory.
hope this help.
Shen HengbinPosted Jan 5, 2012, 12:37 AM
static void Main(string[] args)
{
Test(1);
Console.Read();
}
static string msgformat = "The number is {0}, the square root of that number is {1}";
static void Test(int value)
{
if (value > 20) return;
Console.WriteLine(msgformat , value , value * value);
Test(value + 1);
}