C
Curious
When I select File->New->Project, and then if I pick "Console
Application", it automatically creates a file, "Program.cs".
The content is below:
class Program
{
static void Main(string[] args)
{
StreamReader sr = null;
try
{
double d = 45.66778;
d = RoundToTwoDecimalPlaces(d);
console.WriteLine(d.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
double RoundToTwoDecimalPlaces(double val)
{
// val contains your given value
// we declare a string that contains the truncated value
string decimal_adjusted = val.ToString("N4");
double val_adjusted = double.Parse(decimal_adjusted);
return val_adjusted;
}
}
It won't even compile. The error is:
"An object reference is required for the nonstatic field, method, or
property 'IO.Program.RoundToTwoDecimalPlaces(double)'"
I must create a new class such as "MyNumeric", and add the method
"RoundToTwoDecimalPlaces" to this class. Then I must create in "Main"
an instance of "mn" and use "d=mn.RoundToTwoDecimalPlaces(d);"
It seems that in order to make the code compile, I have to create a
new class and access the method "RoundToTwoDecimalPlaces" from that
class. This doesn't make sense to me- It's a generic math function and
shouldn't be attached to any class.
Anyone agree with me on this?
Application", it automatically creates a file, "Program.cs".
The content is below:
class Program
{
static void Main(string[] args)
{
StreamReader sr = null;
try
{
double d = 45.66778;
d = RoundToTwoDecimalPlaces(d);
console.WriteLine(d.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
double RoundToTwoDecimalPlaces(double val)
{
// val contains your given value
// we declare a string that contains the truncated value
string decimal_adjusted = val.ToString("N4");
double val_adjusted = double.Parse(decimal_adjusted);
return val_adjusted;
}
}
It won't even compile. The error is:
"An object reference is required for the nonstatic field, method, or
property 'IO.Program.RoundToTwoDecimalPlaces(double)'"
I must create a new class such as "MyNumeric", and add the method
"RoundToTwoDecimalPlaces" to this class. Then I must create in "Main"
an instance of "mn" and use "d=mn.RoundToTwoDecimalPlaces(d);"
It seems that in order to make the code compile, I have to create a
new class and access the method "RoundToTwoDecimalPlaces" from that
class. This doesn't make sense to me- It's a generic math function and
shouldn't be attached to any class.
Anyone agree with me on this?