每行读取int并显示百分比

时间:2016-10-26 15:55:02

标签: c++ file-io int percentage fileinputstream

所以,我正在尝试创建一个程序,它读取一个名为“input.txt”的文件,其整数存储如下,并计算它们中有多少百分比大于零,小于零,等于零。

246c

这是我的代码:

使用namespace std;

10
-4
0
34
42
-2
0

和outout:

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;

我仔细检查了我的代码并尝试诊断为什么会这样,但我找不到任何问题。我做错了什么?

1 个答案:

答案 0 :(得分: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;
}