I'm taking a module that involves computational chemistry this term and part of the work for this course involves using C++. We've been set a basic assignment to create a programme that will sum, average (mean) and find the standard deviation of 5 numbers. I've done this, and it seems to work, but was hoping some of you guys could look over what I've done and give me any tips regarding good practice/better ways of doing things?
(It has to compile on Visual C++ 6 since that's what's on the uni network and my laptop is currently out of action...)
// Coursework 1a.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
//standard namespace, compiled in MS VC++6 which does not support this so std:: must be used
using namespace std;
int main()
{
Begin:
//declaring variables
float var1;
float var2;
float var3;
float var4;
float var5;
//asking for and storing variables
std::cout << "Please enter the first number and press enter";
std::cin >> var1;
std::cout << "Please enter the second number and press enter";
std::cin >> var2;
std::cout << "Please enter the third number and press enter";
std::cin >> var3;
std::cout << "Please enter the fourth number and press enter";
std::cin >> var4;
std::cout << "Please enter the fith number and press enter";
std::cin >> var5;
//ask user what operation to perform
int varop;
std::cout << "Please enter 1 to calculate the sum, 2 to calculate the mean and 3 to calculate the standard deviation and press enter";
std::cin >> varop;
//performing operations
float varout;
float varmean;
if (varop == 1)
{
varout = var1 + var2 + var3 + var4 + var5;
std::cout << "The answer is ";
std::cout << varout;
std::cout << " ";
}
else if (varop == 2)
{
varout = (var1 + var2 + var3 + var4 + var5)/5;
std::cout << "The answer is ";
std::cout << varout;
std::cout << " ";
}
else if (varop == 3)
{
varmean = (var1 + var2 + var3 + var4 + var5)/5;
varout = sqrt((pow((var1 - varmean),2) + pow((var2 - varmean),2) + pow((var3 - varmean),2) + pow((var4 - varmean),2) + pow((var1 - varmean),2))/5);
std::cout << "The answer is ";
std::cout << varout;
std::cout << " ";
}
//error
else if (varop > 3)
std::cout << "Invalid Selection";
//Allow user to exit or process more data
int varexit;
std::cout << "If you wish to enter more data please press 1 and then enter, if you wish to exit please press 2 and then enter";
std::cin >> varexit;
if (varexit == 1)
goto Begin;
else if (varexit == 2)
return 0;
else if (varexit > 2)
std::cout << "Invalid Selection";
return 0;
}
Add your 2¢