我的C程序陷入了for循环

时间:2015-02-11 21:56:30

标签: c for-loop infinite-loop

我正在尝试编写一个程序来计算用户提供的三角数。当我运行它时,它会卡在for循环中,但仍会打印出正确的答案,因为我的print语句在循环之外。任何帮助是极大的赞赏。我的代码如下:

#include <stdio.h>

int main (void)
{

    //Declare your variables

    int triangle, triNumber, i;


    //Assign values for known variables

    triNumber = 0;


    //Get the user to input the triangular number that they want

    printf("Please enter the triangular number you would like: ");
    scanf("%i\n", &triangle);


    //Execute for loop that will calculate the triangular number

    for (i = 1; i <= triangle; i = i + 1)
    {
        triNumber = triNumber + 1;
    }


    //Display the user's triangular number

    printf("The triangular number is %i\n", triNumber);

    return 0;

}

1 个答案:

答案 0 :(得分:2)

它没有停留在for循环中。您必须更改scanf()声明:

scanf("%i\n", &triangle);

到此:

scanf("%i", &triangle);
相关问题