Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#for循环跳过一步_C#_For Loop - Fatal编程技术网

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");
    }