c# for循环跳过一步



我正在尝试通过数字循环并计算球体的体积。

用户输入一个数字,然后循环遍历这些数字的卷,直到到达用户的数字。

但是循环跳过第一个数字的计算。

这是我当前的代码

public static float Calculation(float i)
{
//Calculation
float result = (float)(4 * Math.PI * Math.Pow(i, 3) / 3);
//Return the result
return result;
}
static void Main(string[] args)
{
//Declare the result variable in the main method
float result = 0;
//Ask the user to input a number
Console.WriteLine("Please input a number:");
int radius = int.Parse(Console.ReadLine());
//For loop, that runs until i is lesser than or equals to the radius that the user input
for(int i = 0; i <= radius; i++)
{
Console.WriteLine($"The Sphere's volume with radius {i} is {result}n");
//Setting the result by calling the Calculation method and setting the radius to the current i value in the loop
result = Calculation(i);
}
Console.ReadLine();
}

输出为:

The Sphere's volume with radius 0 is 0
The Sphere's volume with radius 1 is 0
The Sphere's volume with radius 2 is 4,1887903
The Sphere's volume with radius 3 is 33,510323
The Sphere's volume with radius 4 is 113,097336
The Sphere's volume with radius 5 is 268,08258
The Sphere's volume with radius 6 is 523,59875
The Sphere's volume with radius 7 is 904,7787
The Sphere's volume with radius 8 is 1436,755
The Sphere's volume with radius 9 is 2144,6606
The Sphere's volume with radius 10 is 3053,6282

将for循环改为:

//For loop, that runs until i is lesser than or equals to the radius that the user input
for(int i = 0; i <= radius; i++)
{
//Setting the result by calling the Calculation method and setting the radius to the current i value in the loop
result = Calculation(i);
Console.WriteLine($"The Sphere's volume with radius {i} is {result}n");
}

你想先计算结果,然后再打印。

谢谢,

最新更新