1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Problem with Variables declaration

Discussion in 'C#' started by whirlwind, Apr 12, 2008.

  1. whirlwind

    whirlwind New Member

    Apr 12, 2008
    Likes Received:
    Trophy Points:
    Hello all,

    I am a newbie in C#, need some advice from you masters.

    Follow is the excercise from my textbook "C Sharp for Students"

    Using the following value:

    double radius = 7.5;

    use assignment statements to calculate the circumference of a circle, the area of a circle and the volume of a sphere, based on the same radius. Display the results with message boxes. The messages should state what the result is rather than merely displaying a number. These calculations involve the use of Pi, which is 3.14 approximately. However, C# provides us with this value to more digits of precision. It is part of the Math class, and the following formulae show its use:

    circumference = 2 * Math.PI * radius;
    area = Math.PI * radius * radius;
    volume = (4 * Math.PI / 3) * radius * radius * radius;

    My codes to the exercise:

            private void button2_Click(object sender, EventArgs e)
                double radius = 7.5;
                double circumference = 2 * Math.PI * radius;
                double area = Math.PI * radius * radius;
                double volume = (4 * Math.PI / 3) * radius * radius * radius;
                MessageBox.Show("Circumference is " + Convert.ToString(circumference));
                MessageBox.Show("Area is " + Convert.ToString(area));
                MessageBox.Show("Volume is " + Convert.ToString(volume));

    Did it look OK to you?

    What I am not happy about is my declaration of variables, is it correct (in a way) to have them all as double? But then the results rather messy i.e. more than 2 digits after the decimal point.

    I left radius as double and changed the rest to integer but received the following error

    Error     1          Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
    Is there a way to have the result with only 2 decimal places rather than e.g. circumference is 47.1238898038469

    Thanks a lot for your advice

Share This Page