Reputation: 511
When I run this program and input, for example, the number 7, the final cout command only works occasionally. Otherwise, the program exits successfully but the result is not printed. Why is this happening?
#include <iostream>
#include <cmath>
double treble(double);
int main()
{
using namespace std;
cout << "Enter a number:" << endl;
double numways;
cin >> numways;
numways = treble(numways);
cout << "Your number trebled is: " << numways << endl;
return 0;
}
double treble(double n)
{
return n * 3;
}
Upvotes: 0
Views: 1809
Reputation: 355
try with this => put
int temp;
cin>>temp;
before return 0;
to pause the program, because the execution finished (successfully) before the last output could be written to the console.
Upvotes: 1
Reputation: 502
You should put using namespace std;
outside of all function declarations, right under your #include
directives. Also, when you say it's not printing, is it that the console is closing before displaying your result? In that case, I would advocate using a simple cin
to "pause" the program. You can do it exactly as @Nihar says, though I might suggest using a string
instead of an int
so that it doesn't break if you accidentally type something other than an int
.
Something like this:
#include <iostream>
#include <cmath>
using namespace std;
double treble(double);
int main(){
cout << "Enter a number:" << endl;
double numways;
cin >> numways;
numways = treble(numways);
cout << "Your number trebled is: " << numways << endl;
string foo;
cin >> foo;
return 0;
}
double treble(double n){
return n * 3;
}
Upvotes: 1