Hey guys. I was asked an apparent simple question asking me to write a program that multiplys the users inputted number by two.
Well, obviously this is harder than I thought, and I think I might need some help.
DO NOT GIVE ME THE ANSWER!
My question is:
Can I put "void" after the "main" function?
The reason why I am asking is because I am concerned that if I put void before main, then when I try and declare a variable, the void function won't be able to read it. I will try out a code, and I will post it to show you what I mean exactly.
Okay, Um... I feel like an idiot. After taking a break. I figured out what I should do:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main()
{
cout << "Please enter a number. Your number will be multiplied by two." << endl;
int a;
cin >> a;
cout << "Your result is " << a * 2 << endl;
cin.get();
return 0;
}
main int() isn't allowed, that's neither a function declaration nor anything else.
If you need the Result function in main, declare it before main. It would make sense for Result to return something, though.
Sorry everyone, the problem was on that page of the website, the tutorial talked about Void and Return Values and such, which I had a little difficulty with. Then at the bottom there was a quiz asking me to create a program that multiplies the number by 2.
Me having such major brain activity, I figured that I would need to include all of that of what I just learned, when really I could do that simple program.
Well, you should use all of what you've learned, especially if you're unsure about the new topic.
Using a separate function could look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int doubleValue(int val)
{
return val*2;
}
int main()
{
cout << "Please enter a number. Your number will be multiplied by two." << endl;
int a;
cin >> a;
cout << "Your result is " << doubleValue(a) << endl;
cin.get();
}
Yes, but that applies only for main. Each function can return a value or an object. The return value of main indicates whether the program was successful - and when main returns, the program exits.
For your own functions, you can freely choose what kind of values they return.
Also, when the end of main is reached without encountering a return statement, 0 will be returned. However, it's important to keep in mind that this is only true for main - other functions won't return any default values - if you have no return statement, the result will be undefined.