创建一个C程序,总结没有数组的正数和负数?

时间:2014-09-29 06:58:05

标签: c

添加所有正数并将其置于变量中的程序 并添加所有负数并将它们放在变量中。最后,该计划应该 打印两个变量中的值,并计算两个变量的平均值。当用户键入零时,程序应该结束。

这是我到目前为止所做的。

int sumPositive, sumNegative;
int n, c = 1;

int main ()
{
    printf("Enter Positive integers:\n");
    scanf("%d", &n);
    for (c = 1; c <=n ; c++)
    {
        scanf("%d",&n);
        sumPositive = sumPositive + n;
    }
    printf("The value of positive numbers is: %d", sumPositive);

    return 0;   
}

3 个答案:

答案 0 :(得分:2)

您的循环应该使用while而不是因为您正在等待输入,而不是更改循环控制变量。所以:

int n, sumPositive = 0, sumNegative = 0;
scanf("%d", &n);
while (n != 0)
{
    //Do your calculations here
    scanf("%d", &n);
}

如果您愿意,还可以通过使用while(true)循环减少编写scanf的次数:

int n, sumPositive = 0, sumNegative = 0;
while(true)
{
    scanf("%d", &n);
    if (n == 0)
        break;
//Rest of calculations
}

正如Jonathan Leffler指出的那样,您应该检查scanf的结果,看看该值是否被正确读取。把它放在循环中的最简单方法是:

int n, sumPositive = 0, sumNegative = 0;
while(scanf("%d", &n) == 1 && n != 0)//Read an n value, check that the read was successful, then check that n != 0
{
//Rest of calculations
}

答案 1 :(得分:1)

抓住:!)

#include <stdio.h>

int main( void )
{
    int x;
    int sumPositive   = 0, sumNegative   = 0;
    int countPositive = 0, countNegative = 0;

    printf( "Enter positive and negative integer numbers (0 - exit): " );

    while ( scanf( "%d", &x ) == 1 && x != 0 )
    {
        if ( x < 0 )
        {
            sumNegative += x;
            countNegative++;
        }
        else
        {
            sumPositive += x;
            countPositive++;
        }
    }

    printf( "\nSum of positive numbers is %d, and their average is %d\n",
            sumPositive, countPositive == 0 ? 0 : sumPositive / countPositive );

    printf( "\nSum of negative numbers is %d, and their average is %d\n",
            sumNegative, countNegative == 0 ? 0 : sumNegative / countNegative );

    return 0;
}

例如,如果要输入

1 -2 3 -4 5 -6 7 -8 9 0

然后输出

Sum of positive numbers is 25, and their average is 5

Sum of negative numbers is -20, and their average is -5

答案 2 :(得分:-1)

while( n != 0) //checking if the user has entered 0 or some other number
{
    scanf("%d",&n);
    //here you have to check whether the entered number is postive ( >0 ) or negative ( <0 )
    //and then accordingly you have to add it to sumPositive or sumNegative,
    //hint: if else will help you
}