Home > other >  c How to find Maximum number and negative numbers from a .txt file and also how to output Total re
c How to find Maximum number and negative numbers from a .txt file and also how to output Total re

Time:10-26

I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only. Im very new and just cant figure out how to do it. This is what i have now

a "numbers.txt" file with

-4
53
-5
-3
2

and

#include <iostream>
#include <fstream>
using namespace std;


int main() {



    int n = 0;
    int sum = 0, total = 0;


    fstream file("numbers.txt");
    while (file >> n) 
    {
        sum  = n;
        total  ;

        

    }

    int average = (float)sum / total;
    int AmountOfNumbersAdded = total;
    int Highest;
    int Negative;


    cout << "Total result: " << sum << endl;
    cout << "Numbers added: " << AmountOfNumbersAdded << endl;
    cout << "Average number: " << average << endl;
    cout << "Maxiumum number: " <<  endl;
    cout << "Negative numbers: " << endl;

    return 0;

}

i tried to do

float Highest = INT_MIN;
        if (Highest < num[i]) {
            Highest = num[i]; 

but it just wouldn't work.

CodePudding user response:

You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.

int Highest = INT_MIN;
int Negative = 0;
while (file >> n) 
{
    sum  = n;
    total  = 1;
    if (n < 0)
    {
         Negative  = 1;
    }
    if (n > Highest)
    {
        Highest = n;
    }
}

float average = (float)sum / total;

CodePudding user response:

Here's what you're looking for.

#include <iostream>
#include <fstream>

int main()
{
  int n = 0;
  int sum = 0, total = 0;
  int highest = 0;
  int negatives = 0;


  std::fstream file("numbers.txt");
  while (file >> n)
  {
    if (n > highest) highest = n;
    if (n < 0)   negatives;
    sum  = n;
      total;
  }

  int average = (float)sum / total;
  int AmountOfNumbersAdded = total;

  std::cout << "Total result: " << sum << "\n";
  std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
  std::cout << "Average number: " << average << "\n";
  std::cout << "Maxiumum number: " << highest << "\n";
  std::cout << "Negative numbers: " << negatives << "\n";

  file.close();
  return 0;
}

As you're new, few advices for you:

  1. Never use using namespace std.
  2. Prefer using "\n" instead of std::endl.
  3. Don't forget to close any files/database after opening them like you did in your code.
  4. Always try to avoid macros.
  • Related