Any easier way of averaging?

This is the code from the book I had bought today "Object Oriented Programming with C++ by E Balagurusamy":

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
    float number1, number2, sum, average;
    cout << "Enter two numbers: ";
    cin  >> number1;
    cin  >> number2;

    sum = number1 + number2;
    average = sum/2;

    cout << "Sum = " << sum << "\n";
    cout << "Average = " << average << "\n";

    return 0;
}
Last edited on
Any easier way of averaging?


I don't know. Do you?
I mean, the code?
Can't get much simpler but you could try using one line and ignoring the variable sum completely, like so,

average = (number1 + number2)/2;

It is all about clarity. You can have different levels of clarity, which basically relates to how much you need to think about a line of code to figure out what it is doing.

Examples usually split things up to make things clearer, and in general clarity is something to keep in mind while writing code. Making a single line with too complicated a formula can make it much more difficult to fix or change later, particularly if someone else is trying to work with your code.
Last edited on
Thanks for clearing that up. "CLARITY." I should write that down.
Topic archived. No new replies allowed.