我能够倒数到零,但我也希望能够输入一个负数,并将其计数到零

时间:2015-03-20 18:28:32

标签: c

我正在尝试编写一个程序,允许用户在负五和正五之间输入任意数字,然后将所选数字计为零。

#include <stdio.h>
#include <unistd.h>

int main()
{
    int start;

    do
//Asking for user input 1-5
    {
        printf("Need Number to start the countdown (1 - 5): ");
//Receiving user input
        scanf("%d",&start);
    }
//while the number is less than the number 6
    while(!(start<6));

    do
//Begin countdown
    {
        printf("%d\n",start);
        start--;
    }
    while(start>0);
//Displaying the number Zero when done
    printf("0\n");
    return(0);
}

2 个答案:

答案 0 :(得分:2)

这应该在CodeReview网站上,但首先你的初始输入循环有问题

while(!(start<6));

允许用户输入类似-1,234,567的值,因此需要

while(start < -5 || start > 5);

那就是说,用最简单的形式你只需要一个if语句

if (start > 0)
{
    // code to count down
}
else if (start < 0)
{
    // code to count up
}
else
{
    print("All Done"); // user entered zero
}

答案 1 :(得分:1)

试试这个例子:

#include <stdio.h>
int main()
{
    int start = -6;
    int increment;

//Asking for user input -5 to +5
    while(start < -5 || start > 5)
    {
        printf("Enter number to start the countdown (1 - 5): ");
        scanf("%d",&start);
    }

    increment = (start < 0) ? +1 : -1;
//while the number is not just past zero
    while(start != increment)
    {
        printf("%d\n",start);
        start += increment;
    }
    return 0;
}