c語言,從鍵盤輸入若干個整數,用-1作為輸入結束的標誌,求他們的和及平均值

c語言,從鍵盤輸入若干個整數,用-1作為輸入結束的標誌,求他們的和及平均值

#include
int main(void)
{
int count=0,n,sum=0;
whlie(scanf(“%d”,&n)!=EOF)
{
if(n==-1)
break;
else sum+=n;
count++
}
printf(“%d,%lf\n”,sum,sum*1.0/count);
return 0;
}

輸入n個整數,求輸入正數之和,負數之和,並統計相應正數和負數的個數,以輸入0表示輸入結束.

C版本:
#include
int main(){
int numPos = 0,sumPos = 0,numNeg = 0,sumNeg = 0,in;
printf(“Please key in the integers,key in 0 to stop:\n”);
do{
scanf(“%d”,&in);
if(in > 0){
numPos++;
sumPos += in;
}
else if(in < 0){
numNeg++;
sumNeg += in;
}
}while(in!= 0);
printf(“There are %d positive integers,whose sum is %d.\n”,numPos,sumPos);
printf(“There are %d negative integers,whose sum is %d.\n”,numNeg,sumNeg);
return 0;
}
borland C版本5.5編譯通過.
Java版本:
import java.util.Scanner;
public class test{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int numPos = 0,sumPos = 0,numNeg = 0,sumNeg = 0,in;
System.out.println(“Please key in the integers,0 to stop”);
do{
in = sc.nextInt();
if(in > 0){
numPos++;
sumPos += in;
}
else if(in < 0){
numNeg++;
sumNeg += in;
}
}while(in!= 0);
System.out.println(“There are”+ numPos +“positive integers,whose sum is”+ sumPos);
System.out.println(“There are”+ numNeg +“negative integers,whose sum is”+ sumNeg);
}
}
JGrasp版本1.8.6_10編譯通過.