簡體   English   中英

創建一個C程序,將沒有數組的正數和負數相加?

[英]Create a C program that sums up the Positive and Negative Numbers Without arrays?

一個程序,將所有正數相加並將其放置在變量中,然后將所有負數相加並將其放置在變量中。 最后,程序應打印兩個變量中的值,並計算兩個變量的平均值。 當用戶鍵入零時,程序應結束。

到目前為止,這就是我所擁有的。

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

您的循環可能應該使用while而不是for,因為您正在等待輸入,而不更改循環控制變量。 所以:

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
}

抓住!:)

#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
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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM