patterncppMinor
Compute the number of molecules
Viewed 0 times
moleculesnumberthecompute
Problem
I would like my program to be reviewed. I had to write a simple program that calculates the number of molecules in a hydrocarbon.
- 1 carbon atom has 12 AMU.
- 1 hydrogen atom has 1 AMU.
#include
using namespace std;
int main()
{
cout > mass >> carbonAtoms >> hydrogenAtoms;
long formulaWght = (carbonAtoms * 12) + (hydrogenAtoms * 1);
double molecules = (mass / formulaWght) * 6.02e23;
cout << mass << " grams of hydrocarbon\nwith "
<< carbonAtoms << " carbon atom(s) and "
<< hydrogenAtoms << " hydrogen atom(s)\ncontains "
<< molecules << " molecules" << endl;
return 0;
}Solution
- Do not use
using namespace std. Read
this
-
Instead of using "magic numbers" in your program. Use symbolic
constants.
CARBON_AMU and HYDROGEN_AMU should be ints. const int CARBON_AMU= 12;
const int HYDROGEN_AMU = 1;
const double AVOGADRO = 6.02214141070409084099072e23;-
Utilize functions in your program, instead of initializing a
variable with an expression:
long formulaWeight(int carbonAtoms, int hydrogenAtoms){
return((carbonAtoms * CARBON_AMU) + (hydrogenAtoms * HYDROGEN_AMU));
}
double numMolecules(float mass, long formulaWeight)
{
return((mass / formulaWeight) * AVOGADRO);
}-
`(e.g. 10.5 2 6): "
-
Fix your indentation. This is much easier to read:
cout << mass << " grams of hydrocarbon\nwith "
<< carbonAtoms << " carbon atom(s) and "
<< hydrogenAtoms << " hydrogen atom(s)\ncontains "
<< molecules << " molecules" << endl;Code Snippets
const int CARBON_AMU= 12;
const int HYDROGEN_AMU = 1;
const double AVOGADRO = 6.02214141070409084099072e23;long formulaWeight(int carbonAtoms, int hydrogenAtoms){
return((carbonAtoms * CARBON_AMU) + (hydrogenAtoms * HYDROGEN_AMU));
}
double numMolecules(float mass, long formulaWeight)
{
return((mass / formulaWeight) * AVOGADRO);
}cout << mass << " grams of hydrocarbon\nwith "
<< carbonAtoms << " carbon atom(s) and "
<< hydrogenAtoms << " hydrogen atom(s)\ncontains "
<< molecules << " molecules" << endl;Context
StackExchange Code Review Q#65332, answer score: 4
Revisions (0)
No revisions yet.