beginner Cout

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Down South
    New Member
    • Dec 2006
    • 3

    beginner Cout

    Hi,

    I am using Dev-C++ 4.9.9.2, when compiling and running the following code,
    [CODE=cpp]#include <cstdio>
    #include <cstdlib>
    #include <iostream>
    using namespace std;
    int main(int nAverage, int a, int b, int c)
    {
    nAverage=((a+b+ c)/3);
    cout << "Please enter first numerical Value: ";
    cin >> a;
    cout << "Please enter the second numerical Value: ";
    cin >> b;
    cout << "Please enter the third numerical Value: ";
    cin >> c;
    cout << "The average is: " << nAverage <<endl;
    return 0;
    }[/CODE]
    I do not get the average in cout, the cmd screen closes after accepting the inputs.
    Borland works fine.
    What is wrong?
    Thanks
    Last edited by Ganon11; Feb 13 '08, 02:55 PM. Reason: Please use the [CODE] tags provided.
  • mkborregaard
    New Member
    • Sep 2007
    • 20

    #2
    You do not define the nAverage function correctly - what your code does is telling the compiler that nAverage is a variable of type int. You then give this int variable the value a+b+c, which are undefined.
    Instead nAverage should be a function returning a double (since the average is not likely to be an integer).
    The correct way of defining your function is: [CODE=cpp]double nAverage (int a, int b, int c) {return (a+b+c)*1.0/3;}[/CODE] .
    You can then call the function using
    Code:
    nAverage(a,b,c)
    The main() function does not take arguments (unless you want to pass them directly from the command prompt), and so they should be deleted.

    Comment

    • Down South
      New Member
      • Dec 2006
      • 3

      #3
      Thanks, will try that straight away...

      Comment

      • mkborregaard
        New Member
        • Sep 2007
        • 20

        #4
        By the way, it looks like you are saying that when you run within the Borland IDE you do not have problems, but otherwise your window shuts down too fast. If that is your problem, you should end the main() function (before return 0;) with the line
        [code=cpp]system("PAUSE")[/code] if your are on ms windows, or just [code=cpp]cin.get();[/code]
        That will make sure the window stays open until you have seen the results.
        You do not need to include <cstdio> when you are using c++ io capabilities (in <iostream>).

        Comment

        Working...