patterncppMinor
Gas cost calculator
Viewed 0 times
gascostcalculator
Problem
I am refreshing my university knowledge on C++ due to a job interview and I am trying to understand everything in depth. Is there any reason for me to use pointers and dynamic memory features of C++ in this example?
It's not that clear to me when should I use these features.
It's not that clear to me when should I use these features.
#include
using namespace std;
int main(){
const int range = 100; // Consumption is lt/100km
double * km = new double;
double * consumption = new double;
double * gas_price = new double;
double * gas_cost = new double;
cout Enter distance in km: ";
cin >> *km;
cout Enter consumption (l/100km): ";
cin >> *consumption;
cout Enter gas price in euros: ";
cin >> *gas_price;
*gas_cost = *consumption * *gas_price * *km /range ;
cout Gas cost: [" << *gas_cost << "€]";
cout << endl;
}Solution
In this minimal of an example, I would not use pointers or dynamic memory features.
As I read this code, I am more concerned about the fact that the code is not divided into logical functions instead of having
You should not use
You should also not have
Additionally, I would probably just initialize the values with
This will validate the
Validation is very important if your program expects input with certain specifications (in this case, it both expects a
As I read this code, I am more concerned about the fact that the code is not divided into logical functions instead of having
main handle everything and that you are using namespace std;.You should not use
using namespace std; in your code, but rather specify which namespace you are using like this: std::cout. If you do use this, it can cause many problems.You should also not have
main handle all the work. You could, for example, have a method to calculate the gas cost, and pass it any required parameters.Additionally, I would probably just initialize the values with
-1.double consumption = -1;
do {
std::cout Enter consumption (l/100km): ";
std::cin >> consumption;
if (!std::cin) {
std::cin.clear();
std::string s = "";
getline(std::cin, s);
}
while (consumption > 100 || consumtion < 1);This will validate the
consumption input, and also not let your program crash if the user inputs a string.Validation is very important if your program expects input with certain specifications (in this case, it both expects a
double and a value with a specific range).Code Snippets
double consumption = -1;
do {
std::cout << "-> Enter consumption (l/100km): ";
std::cin >> consumption;
if (!std::cin) {
std::cin.clear();
std::string s = "";
getline(std::cin, s);
}
while (consumption > 100 || consumtion < 1);Context
StackExchange Code Review Q#82304, answer score: 5
Revisions (0)
No revisions yet.