Thursday, April 18, 2013

Write a c++ program that calculates the average of three numbers


Program to find average of 3 numbers in c++






#include <iostream>
using namespace std;

const int NUM_SCORES = 3;

int main()
{
   int score1, score2, score3;
   float ave;
   cout << "Enter 3 scores separated by spaces: ";
   cin  >> score1 >> score2 >> score3;

   ave = float(score1 + score2 + score3) / float(NUM_SCORES);

   cout << "The average of " << score1 << ", " << score2 << ", and "
        << score3 << " is " << ave << "." << endl;
   return 0;
}




OUTPUT:

Enter 3 scores separated by spaces: 89
56
885
The average of 89, 56, and 885 is 343.333.






---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

--------------------------------
Need help writing a C++ code using loops that 
Write a C++ program to enter 3 integers then computes Write a program that will calculate the average of 3 integers 
C++ Program Which Calculates The Average And Sum Of 3 integers 
c++ loop - C++ Forum‎ 
my project - C++ Forum‎ 
HOW TO WRITE THIS PROGRAM? - C++ 
Find average, Using array's and function 

2 comments:

  1. you could have easily generalized this to work with a vector if doubles to average the whole vector. also, you should be using a double for better precision.
    #include
    #include
    #include
    #include
    typedef std::vector VD;
    double average(VD vdItems) {
    double sum=0;
    for (uint64_t i=0; i < vdItems.size(); i++) {
    sum += vdItems[i];
    }
    return sum/double(vdItems.size())
    }
    double stringtodouble(std::string s) {
    double n;
    std::istringstream (s)>>n;
    return n;
    }


    int main(int argc, char * argv) {
    double n;
    VD elements;
    argc--;argv++;
    if (0==argc) {
    std::cout<<"arguments should be values you wish to average. supply at least 1 argument.\n"
    }
    for (int i=0; i < argc; i++) {
    elements[i]=stringtodouble(argv[i]);
    }
    std::cout<<"average="<<average(elements)<<std::endl;
    return 0;
    }

    ReplyDelete
  2. Please can you give me a code that calculates the average scores of 20 students in 15 subjects?

    ReplyDelete