Write the following code using c #,Write a method that accepts an argument of type double. The method will calculate and display the volume of a sphere with radius specified by its argument. [V=4/3 πr^3]. Call this method from your main three times, with arguments 1, 2, and 10 respectively. The answers are 4.1888, 33.5103 and4188.7902 respectively. Use Math.PI for the value of π
时间: 2024-02-13 18:02:02 浏览: 95
Sure, here's the code in C#:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
CalculateAndDisplaySphereVolume(1);
CalculateAndDisplaySphereVolume(2);
CalculateAndDisplaySphereVolume(10);
}
static void CalculateAndDisplaySphereVolume(double radius)
{
double volume = (4.0 / 3.0) * Math.PI * Math.Pow(radius, 3);
Console.WriteLine($"The volume of a sphere with radius {radius} is {volume:F4}");
}
}
```
This code defines a `CalculateAndDisplaySphereVolume` method that takes a `double` argument `radius` and uses the formula for the volume of a sphere to calculate the volume. The method then displays the result with 4 decimal places using the `Console.WriteLine` method.
The `Main` method then calls this method three times with arguments of 1, 2, and 10, respectively, to calculate and display the volume of spheres with different radii. The answers are 4.1888, 33.5103, and 4188.7902, respectively, which are rounded to 4 decimal places using the `F4` format specifier.
阅读全文