每行读取int并显示百分比
Reading int per line and displaying percentage
所以,我目前正在尝试编写一个程序,它读取一个名为"input.txt"的文件,其中存储的整数如下,并计算它们中大于零,小于零和等于零的百分比。
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;
和文稿:
There were 1864443476.0% negative numbers.
There were 204178000.0% numbers equal to zero.
There were 0.0% numbers greater than zero.
我仔细检查了我的代码,并试图诊断为什么会这样,但我找不到任何问题。我做错了什么?
这是你的代码和每个人的评论放在一起供你学习。
// 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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- 显示零值的变量百分比
- Qt在状态栏中显示不断更新的百分比
- 无法显示循环中数组的正确百分比或总数
- 显示C++程序中流程完成的百分比
- 添加选项以显示百分比时出现生成文件问题
- *忽略* C++和 C# 如何在命令行中显示百分比
- c++程序显示投票的百分比不显示正确的结果
- 每行读取int并显示百分比
- 我如何创建一个c++代码,允许用户输入几个百分比分数,然后显示相应的字母分数