Hello dear C# programmers, I am kinda a beginner to C#, so
I need your help, I really can not figure out why the calculations for
sphere get's me the wrong result, the cube works just fine, but I am having
a problem with the result of sphere's volume.
Any suggestion's, comments are welcome, thank you for your time.

Here is the code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pro2_Lab6
{
    class Shape
    {
        //data
        double data; //expresses the one side of a cube or the radius of a sphere
        string shape; //cube or sphere
        
        //constructors
        public Shape() 
        {
            data = 0.0;
            shape = "";
        }

        //methods
        public void Calcs(out double area)
        {
            Console.WriteLine("Please enter the type of shape: ");
            shape = Console.ReadLine();
            
            switch (shape)
            {
                case("sphere"):
                    Console.WriteLine("Please enter the sphere's radius: ");
                    this.data = Double.Parse(Console.ReadLine());
                    area = ((4/3)*Math.PI)*Math.Pow(this.data,3);
                    break;
                case("cube"):
                    Console.WriteLine("Please enter the one side of the cube: ");
                    this.data = Double.Parse(Console.ReadLine());
                    area = Math.Pow(this.data,3);
                    break;
                default:
                    area = 0.0;
                    Console.WriteLine("\nWrong shape choise!");
                    break;
            }
        }

        public string GetShape()
        {
            return this.shape;
        }
    }

    class Program
    {
        static void Main()
        {
            Shape sx1 = new Shape();
            double volume;
            
            sx1.Calcs(out volume);
            
            if (volume != 0.0)
                Console.WriteLine("O {0} has a volume of {1:.0}", sx1.GetShape(), volume);
 
            Console.ReadKey();
        }
    }
}

Recommended Answers

All 2 Replies

area = ((4/3)*Math.PI)*Math.Pow(this.data,3);

In C#, unless you tell it, numbers without decimal points are treated as integers. So when it evaluates this statement it goes "hmm, integer 4 divided by integer 3. That gives 1".

So change that to

area = ((4.0/3.0)*Math.PI)*Math.Pow(this.data,3);

Thank you for your quick and useful response, sorry if I posted thread in the wrong area, but I am also new to daniweb. That was the problem? uhhh.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.