How do i find the highest ratio in a file using c++? I have the code that alread
ID: 3786295 • Letter: H
Question
How do i find the highest ratio in a file using c++?
I have the code that already averages out the info in a certain txt file:
I understand that i could use an 'if' statement to sort out the info, but how would that be written?
this is the info in the txt file:
10
52 58
145 70
261 90
98 66
78 35
99 45
233 130
66 25
42 15
307 180
(the "10" is number of lines; first column represents the total_number_of_monsters_killed; second column represents the total_number_of_minutes_played ).
Explanation / Answer
The complet C++ code
#include <iostream>
#include <fstream>
using namespace std;
//TODO:
//Write the game with the best monster kill / time ratio to a file
void main() // int main()
{
ifstream in_file;
in_file.open("lol_stats.txt");
int number_of_games_played = 0;
in_file >> number_of_games_played;
double total_number_of_monsters_killed = 0.0;
double total_number_of_minutes_played = 0.0;
double Best_ratio = 0.0; // variable to store the best ratio
double Best_monster_kills = 0.0;// variable to store monster_kills for best ratio
double Best_time_in_minutes = 1.0;// variable to store time_in_minutes for best ratio
for (int i = 0; i < number_of_games_played; i++)
{
double monster_kills, time_in_minutes, ratio;
in_file >> monster_kills;
in_file >> time_in_minutes;
total_number_of_monsters_killed += monster_kills;
total_number_of_minutes_played += time_in_minutes;
ratio = monster_kills/time_in_minutes;// Evaluating the ratio
if(Best_ratio < ratio) // Find the best ratio by comparison
{
Best_ratio = ratio; // updating the Best ratio
Best_monster_kills = monster_kills;// updating the Best_monster_kills
Best_time_in_minutes = time_in_minutes;// updating the Best_time_in_minutes
}
}
double avg_number_of_monsters_killed_per_minute = 0.0;
avg_number_of_monsters_killed_per_minute = total_number_of_monsters_killed / total_number_of_minutes_played;
cout << "avg_number_of_monsters_killed_per_minute: " << avg_number_of_monsters_killed_per_minute << endl;
cout << " The highest ratio = " << Best_monster_kills << "/" << Best_time_in_minutes << " = " << Best_ratio << endl;// result
getch(); //return 0;
}
OUTPUT
avg_number_of_monsters_killed_per_minute: 1.93417
The highest ratio = 261/90 = 2.9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.