C#for循环跳过一步
我试图通过数字循环,计算球体的体积 用户输入一个数字,然后在数字卷中循环,直到达到用户的数字 但是,循环跳过了第一个数字的计算 这是我目前的密码C#for循环跳过一步,c#,for-loop,C#,For Loop,我试图通过数字循环,计算球体的体积 用户输入一个数字,然后在数字卷中循环,直到达到用户的数字 但是,循环跳过了第一个数字的计算 这是我目前的密码 public static float Calculation(float i) { //Calculation float result = (float)(4 * Math.PI * Math.Pow(i, 3) / 3); //Return the result retur
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();
}
将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");
}
//对于循环,它一直运行到i小于或等于用户输入的半径
对于(int i=0;i)您希望在打印之前首先获得结果。另外,在循环内声明result
var result=Calculation(i);
这很有效,谢谢。
//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");
}