2016-03-10 3 views
-6

«Количество положительных и отрицательных чисел и вычисление среднего числа чисел. Напишите программу, которая читает неопределенное число целых чисел, определяет, сколько положительных и отрицательных значений было прочитано, и вычисляет общее и среднее значение входных значений (не считая нулей). Ваша программа заканчивается на входе 0. Отображает среднее значение как двойное. Где я ошибся?C++, подсчет положительных и отрицательных чисел и вычисление среднего числа чисел) Напишите программу, которая читает неопределенное число целых чисел

#include <iostream> 
using namespace std; 
int main() 

{ 
      int num= 0; 
      int sum=0; 
      int pos=0; 
      int neg=0; 
      double ave=0; 
      cout << "Enter an integer, the input ends if it is 0: " ; 
      cin >> num ; 
      if (num%10==10) { 
       while (num!=0) { 
        num/=10; 
        if (num%10>0) { 
         pos++; 
        } 
      else if (num%10<0) { 
       neg++; 
      } 
      sum+=num; 
       } 
      ave= (double)sum/(pos+neg); 
      } 
      cout <<"The number of positives are " << pos <<endl; 
      cout <<"The number of negatives are " << neg <<endl; 
      cout <<"The total is " << sum << endl; 
      cout <<"The average is "<< ave << endl; 
      return 0; 

} 
+1

И ваш вопрос? – NathanOliver

+0

Где я ошибся? –

+1

Как мы должны знать? Вы не сказали, что делает ваш код и что он должен делать. – NathanOliver

ответ

0

Вы можете использовать char[] для чтения ввода Я изменил свою программу следующим образом.

int main() 
{ 
    int sum=0; 
    int pos=0; 
    int neg=0; 
    double ave=0; 
    char arr[100] = {'\0',}; 

    std::cout << "Enter an integer, the input ends if it is 0: " ; 
    gets(arr); 

    int index = 0; 
    char ch[1]; 
    bool negativeNumber = false; 

    while(true) 
    {    
     ch[0] = arr[index++]; 
     if(ch[0] == ' ') // Check space and continue; 
     { 
      continue; 
     } 
     else if(ch[0] == '0' || ch[0] == '\0') // check for 0 or NULL and break; 
     { 
      break; 
     } 
     if(ch[0] == '-') // Set flag if "-ve" 
     {   
      negativeNumber = true; 
      continue; 
     } 

     int digit = atoi(ch); 
     if(negativeNumber) 
     { 
      digit *= -1; 
      negativeNumber = false; 
     } 
     if(digit > 0) 
     { 
      pos++; 
     } 
     else if(digit < 0) 
     { 
      neg++; 
     } 
     sum += digit; 
    } 
    ave= (double)sum/(pos+neg); 

    cout <<"The number of positives are " << pos <<endl; 
    cout <<"The number of negatives are " << neg <<endl; 
    cout <<"The total is " << sum << endl; 
    cout <<"The sverage is "<< ave << endl; 

    return 0; 
} 

Надеюсь, это поможет.

+0

где это анои (ch) объявлено? –

+0

atoi() - это предопределенная функция, которая преобразует указатель char в тип int. –

Смежные вопросы