2016-10-26 8 views
1

Итак, в настоящее время я пытаюсь создать программу, в которой он читает файл под названием «input.txt» с целыми числами, хранящимися следующим образом, и вычисляет, сколько процентов из них больше нуля, меньше, чем нуль и равна нулю.Чтение int в строке и отображение процента

10 
-4 
0 
34 
42 
-2 
0 

вот мой код:

с использованием патезраса;

ifstream inputFile; 
int count = 0; 
int value,negative,positive,zero; 
double negPerc,posPerc,zeroPerc; 

inputFile.open("input.txt"); 
if (!inputFile.fail()){ 

    while (inputFile >> value) 
      { 
      count++; 

      if(value < 0) 
       negative++; 
      if(value == 0) 
       zero++; 
      if(value > 0) 
       positive++; 

      } 

     } 
else 
{ 
    cout << "\nError, unable to open input file "; 
} 

cout << fixed << setprecision(1); 

negPerc = (negative/count)*100; 
posPerc = (positive/count)*100; 
zeroPerc = (zero/count)*100; 


cout << "There were " << negPerc << "% negative numbers." << endl; 
cout << "There were " << zeroPerc << "% numbers equal to zero." << endl; 
cout << "There were " << posPerc << "% numbers greater than zero." << endl; 

и Outout:

There were 1864443476.0% negative numbers. 
There were 204178000.0% numbers equal to zero. 
There were 0.0% numbers greater than zero. 

я дважды проверил мой код и пытался диагностировать, почему это так, но я не смог найти каких-либо проблем. Что я делаю не так?

+2

Разделения - это 'int/int', которые будут обрезаны до' int'. Отбросьте одну из них до 'double' * before * the division. Например, вы можете записать его как '(negative * 100.0)/count;'. Это всего лишь одна ошибка. – BoBTFish

+0

Это целые числа - negative & count - поэтому вы получаете целочисленное деление, чего вы не ожидаете. – UKMonkey

+5

Кроме того, инициализируйте отрицательные, положительные и нулевые значения «0» (например, yo с подсчетом) до их увеличения. Скомпилируйте с -g -Wall и запустите все, о ком компилятор жалуется. Также обратите внимание на «загрязнение пространства имен» (прекратите использование «using namespace std»). – Chris

ответ

0

Вот ваш код со всеми комментариями, собранными вместе для вас, чтобы учиться.

// Compile with "g++ yourCPPfile.cpp -o yourExecName -g -Wall" 
#include <iostream> 
#include <iomanip> 
#include <fstream> 
using std::ifstream; 
#include <cstdio> 
using std::cout; 

int main() { 
    ifstream inputFile; 
    int count, value, negative, positive, zero; 
    count = negative = positive = zero = 0; 
    double negPerc, posPerc, zeroPerc; 

    inputFile.open("input.txt"); 

    if (!inputFile.fail()) { 
     while (inputFile >> value) { 
      count++; 
      if (value < 0) 
       negative++; 
      if (value == 0) 
       zero++; 
      if (value > 0) 
       positive++; 
     } 
    } 
    else { 
     cout << "\nError, unable to open " << inputFile << "!\n"; 
    } 

    // Stays this way until you setPrecision() to something else. 
    cout << std::setprecision(1); 

    // Troubleshooting!! 
    cout << negative << "\n"; 
    cout << positive << "\n"; 
    cout << zero << "\n"; 
    cout << count << "\n"; 

    // Calculations. 
    negPerc = (negative * 100.0/count); 
    posPerc = (positive * 100.0/count); 
    zeroPerc = (zero * 100.0/count); 

    // Your desired result... 
    cout << "There were " << std::fixed << negPerc << "% negative numbers." << "\n"; 
    cout << "There were " << std::fixed << zeroPerc << "% numbers equal to zero." << "\n"; 
    cout << "There were " << std::fixed << posPerc << "% numbers greater than zero." << "\n"; 
    return 0; 
} 

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

  • Нет связанных вопросов^_^