|
konadora
Singapore66117 Posts
I want to start off by saying that I'm quite noob with C++ programming, and I need to revise everything in 4 hours' time. Guides online have more terms introduced than explained, so I'm hoping I'll get more luck here.
First, what's the difference between:
int main()
and
void main()
? I keep seeing int main() being used more often in examples, but in school, I've been only using void main().
Second, why is this invalid?
#include <iostream> using namespace std;
void main() { int x; cout << "Please enter an integer." << endl; cin >> x >> endl;
cout << "You have entered "x << endl;
}
I get these errors:
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(10) : error C2146: syntax error : missing ';' before identifier 'x' 1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(10) : error C2563: mismatch in formal parameter list 1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(10) : error C2568: '<<' : unable to resolve function overload
As well as this message while debugging:
1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(974): could be 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> & )' 1> with 1> [ 1> _Elem=wchar_t, 1> _Traits=std::char_traits<wchar_t> 1> ] 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(966): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> & )' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char> 1> ] 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(940): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> & )'
Fixed!
+ Show Spoiler [Fixed ver] +#include <iostream> using namespace std;
void main() { int x; cout << "Please enter an integer." << endl; cin >> x;
cout << "You have entered " << x << endl;
}
I need to revise right from the basics, learning how to do sorts (bubble sorts, insertion sorts, quick sorts, binary search) as well as learning how to use weights, strings etc.
This is one I did quite some time ago, but I didn't revise and completely forgot the reason behind it:
#include <iostream> #include <string> using namespace std;
void main() { char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'}; int weight[8] = { 0,2,7,6,5,4,3,2 }; string nric; int sum=0; // init cumulative sum to zero
// get NRIC input cout << "Enter NRIC: "; getline (cin,nric); cout << nric << endl; // calculate check digit for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0')*weight[i]; } cout << sum << endl; int checkdigit = 11 - (sum%11); // check if the user's NRIC check digit matches to confirm valid nric if (digit[checkdigit]==nric[8]) cout << "valid NRIC number" << endl; else cout << "Invalid NRIC number" << endl; }
Help would be greatly appreciated!!!
   
|
without ever doing c++ and knowledge from other languages i would say the first question is int and void are return types you know int returns an integer and void doesnt return anything
|
using int function will give the result as a integer, that is why return 0 is used a lot when using int main(); But using void main() gives no result im pretty sure. That is how i understand it. ( I think im sure)
|
#include <iostream> using namespace std;
void main() { int x; cout << "Please enter an integer." << endl; cin >> x >> endl;
cout << "You have entered "x << endl;
}
you need to put another "<<" before x on the last line. so change the last line to
cout << "You have entered " << x << endl;
|
konadora
Singapore66117 Posts
I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?
|
konadora
Singapore66117 Posts
Okay I got the short program to work, I foolishly used cin >> x >> endl; instead of cin >> x;
#include <iostream> using namespace std;
void main() { int x; cout << "Please enter an integer." << endl; cin >> x;
cout << "You have entered " << x << endl;
}
|
On June 28 2009 23:42 konadora wrote: I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right?
no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred.
if you make main void, then it has no return type, and will always return 0 to the caller.
|
konadora
Singapore66117 Posts
Oh I see, so it's just that int main() allows you to identify whether your program has an error or not, but void main() can't?
|
void main() should never be used as the main function should ALWAYS return a value
I thought everyone that?!
|
konadora
Singapore66117 Posts
On June 29 2009 00:01 Revabug wrote: void main() should never be used as the main function should ALWAYS return a value
I thought everyone that?! Would you mind explaining a bit more? I already stated that I'm quite noob with C++
|
When you're doing a small project, as is typical for a lot of uni work, what your main function returns basically won't matter. Albeit obviously it's better practice to use int, and bad habits are bad.
|
never use void main. Its oldschool bad programming.
|
konadora
Singapore66117 Posts
Okay, so I've got that cleared. Now, I need to tackle all these 'floats', 'doubles', 'integers', etc. What are the names of these? Are they the 'return data types'?
|
On June 28 2009 23:36 konadora wrote:Show nested quote +#include <iostream> #include <string> using namespace std;
void main() { char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'}; int weight[8] = { 0,2,7,6,5,4,3,2 }; string nric; int sum=0; // init cumulative sum to zero
// get NRIC input cout << "Enter NRIC: "; getline (cin,nric); cout << nric << endl; // calculate check digit for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0')*weight[i]; } cout << sum << endl; int checkdigit = 11 - (sum%11); // check if the user's NRIC check digit matches to confirm valid nric if (digit[checkdigit]==nric[8]) cout << "valid NRIC number" << endl; else cout << "Invalid NRIC number" << endl; } char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'}; creates an array of characters with the length of 12, digit[0] == 'x', digit[1] == 'A', ... , digit[11] == 'J' int weight[8] = { 0,2,7,6,5,4,3,2 }; same with integer values cout << "Enter NRIC: "; getline (cin,nric); here you get an input from the user, he types something on his keyboard, and the input is saved in the string (string = array of char) nric. for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0' )*weight[i]; } this for-loop iterates through the array the user has typed. Its strange, that you dont start with i = 0, since arrays in C, Java and C++ are beginning with the index 0.
|
The only thing int main does is use the int you return as a parameter for ExitProcess (or exit, which is basically a wrapper for ExitProcess). void main will always return 0.
|
konadora
Singapore66117 Posts
On June 29 2009 00:09 treason wrote:Show nested quote +On June 28 2009 23:36 konadora wrote:#include <iostream> #include <string> using namespace std;
void main() { char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'}; int weight[8] = { 0,2,7,6,5,4,3,2 }; string nric; int sum=0; // init cumulative sum to zero
// get NRIC input cout << "Enter NRIC: "; getline (cin,nric); cout << nric << endl; // calculate check digit for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0')*weight[i]; } cout << sum << endl; int checkdigit = 11 - (sum%11); // check if the user's NRIC check digit matches to confirm valid nric if (digit[checkdigit]==nric[8]) cout << "valid NRIC number" << endl; else cout << "Invalid NRIC number" << endl; } char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};creates an array of characters with the length of 12, digit[0] == 'x', digit[1] == 'A', ... , digit[11] == 'J' int weight[8] = { 0,2,7,6,5,4,3,2 };same with integer values cout << "Enter NRIC: "; getline (cin,nric);here you get an input from the user, he types something on his keyboard, and the input is saved in the string (string = array of char) nric. for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0' )*weight[i]; }this for-loop iterates through the array the user has typed. Its strange, that you dont start with i = 0, since arrays in C, Java and C++ are beginning with the index 0. I need help with explanation on the 'arrays' part, I can't find the notes online on my school's e-learning platform. Step-by-step explanation would help so much, I would love you for life
|
On June 28 2009 23:47 AcrossFiveJulys wrote:Show nested quote +On June 28 2009 23:42 konadora wrote: I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right? no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred. if you make main void, then it has no return type, and will always return 0 to the caller. Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.
|
On June 29 2009 00:15 tec27 wrote:Show nested quote +On June 28 2009 23:47 AcrossFiveJulys wrote:On June 28 2009 23:42 konadora wrote: I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right? no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred. if you make main void, then it has no return type, and will always return 0 to the caller. Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int.
You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret)
|
|
On June 29 2009 00:08 konadora wrote: Okay, so I've got that cleared. Now, I need to tackle all these 'floats', 'doubles', 'integers', etc. What are the names of these? Are they the 'return data types'?
you really need to read your textbook. float, double, int, are all variable types. this is a very basic concept, and you won't get far asking such questions here.
|
Okay, so I've got that cleared. Now, I need to tackle all these 'floats', 'doubles', 'integers', etc. What are the names of these? Are they the 'return data types'?
They're just data types, they can be used to return but they're not 'return data types'
|
On June 29 2009 00:16 Uligor wrote:Show nested quote +On June 29 2009 00:15 tec27 wrote:On June 28 2009 23:47 AcrossFiveJulys wrote:On June 28 2009 23:42 konadora wrote: I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right? no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred. if you make main void, then it has no return type, and will always return 0 to the caller. Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int. You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret)
That was my understanding as well. To his defense, of course, if you are using a compiler which does not do this, you might have problems. But overall this is a very petty concept.
|
konadora
Singapore66117 Posts
My teachers didn't explain any of these differences, just gave us terms, they're like, 'put these here and here, you get a program. now try it'.
That's why... :S
What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.
|
On June 28 2009 23:49 konadora wrote: Oh I see, so it's just that int main() allows you to identify whether your program has an error or not, but void main() can't?
This is essentially true. Some people prefer to always use int as it is "good form." Honestly though, if you don't understand the difference yet, which one you use will make no difference at all.
As for the second program, you read in a NRIC, which is apparently some sort of barcode or something. You then check to see if it's valid by using a check digit, a computable extra number added to the string:
int weight[8] = { 0,2,7,6,5,4,3,2 }; for (int i=1; i<=7; i++) sum = sum + ( nric[i] - '0' ) * weight[ i ];
// nric[ i ] is the ith character of the nric // nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0. // You then multiply each digit of the nric by some pre-determined "weight" and add them up. // This algorithm is arbitrary, but as long as it's reproducible any check-digit algorithm is fine.
char digit[ 12 ]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J' }; int checkdigit = 11 - ( sum % 11 ); if( digit[ checkdigit ] == nric[ 8 ] )
// You then take the resulting sum and use modulus arithmetic to reduce it to the range [ 1, 11 ] // Then you look up the character with that index (from 1 to 11) in the "digit" array to get the 'secret' character that belongs with this string. If they match, you then output saying so. Otherwise you output an error.
Examples:
If your NRIC is 12345678H then your sum is 2*2 + 3*7 + 4*6 + 5*5 + 6*4 + 7*3 + 8*2 = 135 (Note that you ignore the first character, since its index is 0 and i starts from 1) Then you see that 135 % 11 = 3, so your "check digit" is 11 - 3 = 8. So you then look up 8 in the digit[] array to get 'H'. You compare the calculate check digit with the check digit at the end of the number. Lo and behold, a match!
Now, if your NRIC is 93843248B then your sum is 2*3 + 3*8 + 4*4 + 5*3 + 6*2 + 7*4 + 8*8 = 165. Then you see that 165 % 11 = 0, so your check digit is 11 - 0 = 11. You look up digit[ 11 ] to get 'J', and compare that to the check digit on the end of the NRIC. They don't match, so clearly I inputted my number wrong.
|
On June 29 2009 00:13 konadora wrote:Show nested quote +On June 29 2009 00:09 treason wrote:On June 28 2009 23:36 konadora wrote:#include <iostream> #include <string> using namespace std;
void main() { char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'}; int weight[8] = { 0,2,7,6,5,4,3,2 }; string nric; int sum=0; // init cumulative sum to zero
// get NRIC input cout << "Enter NRIC: "; getline (cin,nric); cout << nric << endl; // calculate check digit for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0')*weight[i]; } cout << sum << endl; int checkdigit = 11 - (sum%11); // check if the user's NRIC check digit matches to confirm valid nric if (digit[checkdigit]==nric[8]) cout << "valid NRIC number" << endl; else cout << "Invalid NRIC number" << endl; } char digit[12]= { 'x', 'A', 'B','C','D','E','F','G','H','I','Z','J'};creates an array of characters with the length of 12, digit[0] == 'x', digit[1] == 'A', ... , digit[11] == 'J' int weight[8] = { 0,2,7,6,5,4,3,2 };same with integer values cout << "Enter NRIC: "; getline (cin,nric);here you get an input from the user, he types something on his keyboard, and the input is saved in the string (string = array of char) nric. for (int i=1; i<=7; i++) { sum = sum + (nric[i]-'0' )*weight[i]; }this for-loop iterates through the array the user has typed. Its strange, that you dont start with i = 0, since arrays in C, Java and C++ are beginning with the index 0. I need help with explanation on the 'arrays' part, I can't find the notes online on my school's e-learning platform. Step-by-step explanation would help so much, I would love you for life An array is a field of values. Lets say, you want to save 5 numbers: int number1, number2, number3, number4, number5; number1 = 0; number2 = 3; number3 = 7; number4 = 12; number5 = 1; Thats really annoying, you have to write alot and you can make some mistakes if you are sleepy :D Thats why arrays were invented:
int example[5]; example[0] = 0; example[1] = 3; example[2] = 7; example[3] = 12; example[4] = 1;
Thats also to long, you can write it in a shorter way: int example[] = {0,3,7,12,1}; the first line int example[5]; declares a field of integer values with the length of 5, in the next 5 lines i put some values into this field. Now, 5 values are saved into this field, and you can access its content via the [ ] operator. If you want to print the first number, you can do: cout >> number1>> endl; and with the array: cout >> example[0] >> endl; Another good thing about arrays is, that you can use a for-loop the access all contents of the field: for(int i = 0; i<=4; i++){ cout >> example[i] >> endl; } will write: 0 3 7 12 1
on the screen.
|
konadora
Singapore66117 Posts
@ms291052:
// nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0. // You then multiply each digit of the nric by some pre-determined "weight" and add them up. Why is the -0 necessary? (Great first post btw, thanks lol)
@treason: so if you put number[5], you'll have 5 different values, but if you want to access the nth number, you must use number[n-1]?
Also, this part
for(int i = 0; i<=4; i++){ cout >> example[i] >> endl; }
Means that something like:
First, display the 0th line's number, and since it's not greater than example[4], display 0+1 (making it 1th) line's number, and continue until it reaches i = 4 (where it cannot exceed i = 4 and ends there), right?
|
On June 29 2009 00:32 konadora wrote:@ms291052: Show nested quote +// nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0. // You then multiply each digit of the nric by some pre-determined "weight" and add them up. Why is the -0 necessary? (Great first post btw, thanks lol) @treason: so if you put number[5], you'll have 5 different values, but if you want to access the nth number, you must use number[n-1]?
The character '0' has a different value than int 0 (char '0' is in fact 48 int, '1' is 49 etc). But when you subtract the character with '0', you essentially do -48. So when the character is '1' (49), it becomes 49-48 = 1.
|
konadora
Singapore66117 Posts
On June 29 2009 00:38 Uligor wrote:Show nested quote +On June 29 2009 00:32 konadora wrote:@ms291052: // nric[ i ] - '0' is a kind of kludge that will turn a character representation of a digit into a numerical represention of the same digit. That is '9' - '0' = 9 and '6' - '0' = 6, et cetera. Obviously '0' - '0' = 0. // You then multiply each digit of the nric by some pre-determined "weight" and add them up. Why is the -0 necessary? (Great first post btw, thanks lol) @treason: so if you put number[5], you'll have 5 different values, but if you want to access the nth number, you must use number[n-1]? The character '0' has a different value than int 0 (char '0' is in fact 48 int, '1' is 49 etc). But when you subtract the character with '0', you essentially do -48. So when the character is '1' (49), it becomes 49-48 = 1. Oooh, okay thanks, didn't know that!
|
konadora
Singapore66117 Posts
My next question:
What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.
|
On June 29 2009 00:48 konadora wrote:My next question: Show nested quote +What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9.
float or double.
|
konadora
Singapore66117 Posts
Isn't double for numbers with decimal points? What's the difference between float and double?
(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language)
|
On June 29 2009 00:16 Uligor wrote:Show nested quote +On June 29 2009 00:15 tec27 wrote:On June 28 2009 23:47 AcrossFiveJulys wrote:On June 28 2009 23:42 konadora wrote: I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right? no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred. if you make main void, then it has no return type, and will always return 0 to the caller. Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int. You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret) I'm sorry, but you're wrong except for very specific compilers. Microsoft's compiler does this, but the standards do not support that. It was merely done to make bad code that they/other people had written in the past still work.
If you hop over to g++, however, you'll find that you can't even compile a program with 'void main':
voidmain.cpp:1: error: '::main' must return 'int'
Now, what is within the standards is to auto-return 0 for main functions declared as type int (IE: if no return statement is specified inside). While this is still bad practice, it should work on all standards-compliant compilers.
In short, don't encourage someone to not follow standards on a simple matter like this just because a certain compiler will fix the mistake for them. Its incredibly bad practice, and this is the kind of thing that, even though its small, will make lots of people have zero respect for you and your code.
|
On June 29 2009 00:53 konadora wrote: Isn't double for numbers with decimal points? What's the difference between float and double?
(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language) Both double and float are for numbers with decimal points. A double has more precision than a float (IE: can store longer decimals), but is also therefore larger in memory.
Edit: Also, you probably don't need to use a floating-point format at all, you can just plug the 5/9 into the calculation itself.
IE: int celsius = (int)((farenheit - 32) * 5 / 9);
Should work (although it will be truncated to an integer).
|
konadora
Singapore66117 Posts
On June 29 2009 00:58 tec27 wrote:Show nested quote +On June 29 2009 00:53 konadora wrote: Isn't double for numbers with decimal points? What's the difference between float and double?
(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language) Both double and float are for numbers with decimal points. A double has more precision than a float (IE: can store longer decimals), but is also therefore larger in memory. Oh okay, understand now.
Thanks for all the responses so far, I just need to refresh my memory since I did practice quite a bit... a few months ago. Currently doing an exercise, will post questions once again here if I get stuck, can't say this enough but thanks again!
|
On June 29 2009 00:53 konadora wrote: Isn't double for numbers with decimal points? What's the difference between float and double?
(Sorry if these questions are very basic, but no revision + 1 month of missing school + bad teacher = sucky at language)
double and float are for numbers like 1.234, yes. The difference between double and float is float is 32 bit and double is 64 bit.
Maybe I misunderstood your question, you wanted to know what datatype you should use in an algorithm to convert Farenheit temperature into centigrade and viceversa? Or did you want to know how to output a fraction in the console?
On June 29 2009 00:56 tec27 wrote:Show nested quote +On June 29 2009 00:16 Uligor wrote:On June 29 2009 00:15 tec27 wrote:On June 28 2009 23:47 AcrossFiveJulys wrote:On June 28 2009 23:42 konadora wrote: I don't really quite understand the concept of 'returning an integer', what does it mean?
Also, if you go for int main(), you must end off with a return 0; , but if you use void main(), you don't have to, right? no. if you make main's return type int, then you can return any integer you want. the point of this is so that a program that calls your main function (such as the program you are using to test it, like a terminal or visual studio) can retrieve the return value. you can use this communication to return error codes... i.e., return 0 if all goes well, or return > 0 if an error occurred. if you make main void, then it has no return type, and will always return 0 to the caller. Just to be clear here, making main type void makes it return *no* value which is not at all the same as returning 0. At a lower level, the return value of a function is usually stored in a register, therefore, if the operating system (which in this case acts as a 'calling function' expects main to be of type int and calls it that way, it will receive an effectively random value in return if it is type void. As you might imagine, thats a bad thing that just happens to turn out okay sometimes. In short, make your main function type int. You're wrong, the compiler automatically makes the main function return 0 when it's specified as void. (xor eax, eax before ret) I'm sorry, but you're wrong except for very specific compilers. Microsoft's compiler does this, but the standards do not support that. It was merely done to make bad code that they/other people had written in the past still work. If you hop over to g++, however, you'll find that you can't even compile a program with 'void main': Now, what is within the standards is to auto-return 0 for main functions declared as type int (IE: if no return statement is specified inside). While this is still bad practice, it should work on all standards-compliant compilers. In short, don't encourage someone to not follow standards on a simple matter like this just because a certain compiler will fix the mistake for them. Its incredibly bad practice, and this is the kind of thing that, even though its small, will make lots of people have zero respect for you and your code.
It is true that it is compiler specific (I use MSVS08 and I was under the impression kona used this as well, hence the windows explanation of what happens with the exitcode). I apologize because I used "the compiler" instead of specifying the compiler I was talking about, this made it seem like I was belittling your knowledge of compiler specifics.
|
konadora
Singapore66117 Posts
Maybe I misunderstood your question, you wanted to know what datatype you should use in an algorithm to convert Farenheit temperature into centigrade and viceversa?
Yup, which datatype.
Also, fyi, I'm using Microsoft Visual C++ Express Edition.
|
Also, sorry if I'm coming off as rude, Uligor. I just think its a really bad idea to teach newer programmers to use 'void main()' before they even know how it affects anything, since its super-easy to learn the other way at the beginning, but somewhat harder to fix old habits later on.
|
konadora
Singapore66117 Posts
Okay, I've managed to complete the exercise, using this:
#include <iostream> using namespace std;
int main() { double c,f; cout << "Please enter the temperature in Centigrade." << endl; cin >> c; f = ((c*1.8)+32); cout << "The temperature is " << f << " degrees Farenheit." << endl;
cout << "Please enter the temperature in Farenheit." << endl; cin >> f; c = ((f-32)*5/9); cout << "The temperature is " << c << " degrees Centigrade." << endl;
return 0; }
But I want the user to choose which one he's inputting first (whether he's going to input Farenheit or Centigrade), and use that, and end the program. Which loop do I use, and how?
|
I don't think you need to use a loop for that, just use an if/else statement. Just input a character to decide which one to use or whatever and then check it:
if(myChar == 'c' ) { // do Celsius -> Farenheit calculation } else if(myChar == 'f' ) { // do Farenheit -> Celsius calculation } else { // Tell the user to follow instructions, better luck next time  }
|
konadora
Singapore66117 Posts
What is the myChar?
Or is that the 'character'? lol
|
Yeah, thats just the variable you'd be inputting their answer to.
|
konadora
Singapore66117 Posts
I don't quite get how to use it, I got this -
#include <iostream> using namespace std;
int main() { double c,f; cout << "Please choose whether you are entering the temperature in Centigrade (c) or Farenheit (f)." << endl; if(myChar == 'c'){ f = ((c*1.8)+32); cout << "The temperature is " << f << " degrees Farenheit." << endl; } else if(myChar == 'f'){ c = ((f-32)*5/9); cout << "The temperature is " << c << " degrees Centigrade." << endl; } return 0; }
With these errors:
1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(8) : error C2065: 'myChar' : undeclared identifier 1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(12) : error C2065: 'myChar' : undeclared identifier
|
On June 29 2009 00:49 Uligor wrote:Show nested quote +On June 29 2009 00:48 konadora wrote:My next question: What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9. float or double.
yes
at least one of the two numbers must be a float or double, or you must explicitly cast one to a double <static_cast> or integer division will be performed instead.
|
On June 29 2009 01:29 konadora wrote:I don't quite get how to use it, I got this - Show nested quote +#include <iostream> using namespace std;
int main() { double c,f; cout << "Please choose whether you are entering the temperature in Centigrade (c) or Farenheit (f)." << endl; if(myChar == 'c'){ f = ((c*1.8)+32); cout << "The temperature is " << f << " degrees Farenheit." << endl; } else if(myChar == 'f'){ c = ((f-32)*5/9); cout << "The temperature is " << c << " degrees Centigrade." << endl; } return 0; } With these errors: Show nested quote +1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(8) : error C2065: 'myChar' : undeclared identifier 1>c:\users\user\documents\visual studio 2008\projects\p1\p1\p1.cpp(12) : error C2065: 'myChar' : undeclared identifier
The code in this case would be
#include <iostream> using namespace std;
int main() { double value; char myChar;
cout << "Please enter C (Centigrade) or F (Farenheit) followed by the appropriate value" << endl; cin >> myChar >> value;
if(myChar == 'C') cout << "The temperature is " << (value*1.8)+32 << " degrees Farenheit." << endl; else if(myChar == 'F') cout << "The temperature is " << (value-32)*5/9 << " degrees Centigrade." << endl; else cout << "Please insert a correct prefix" << endl;
return 0; }
Please note how I replaced double f/c with double value and how I moved the calculations to inside the cout << instruction. The example input for this piece of code would be "F 1.42". (note: this would be a rather unpleasant temperature)
|
konadora
Singapore66117 Posts
The char is the same as 'int', except it is not just integers, but characters, that's all, right?
Also, the purpose of putting the calculations inside the cout << instruction would be to shorten the entire program, as well as to remove unnecessary variables, right?
Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.
|
On June 29 2009 01:41 konadora wrote: The char is the same as 'int', except it is not just integers, but characters, that's all, right?
char is 8 bit, int is 32 bit (though for int it's compiler specific). I think this might go a bit too far for now, you should use char to save single-byte characters (e.g. 'e', '0', etc).
On June 29 2009 01:41 konadora wrote:Also, the purpose of putting the calculations inside the cout << instruction would be to shorten the entire program, as well as to remove unnecessary variables, right?
Yeah, it's basically to remove unnecessary variables.
|
United States17042 Posts
|
konadora
Singapore66117 Posts
Thanks for all the help for this noob here, I don't think I can keep awake anymore, already drank 4 cups of coffee. Will wake up in 6 hours' time and continue from there, going to get some sleep (almost 1am here). Thanks all once again!
|
On June 29 2009 01:41 konadora wrote: The char is the same as 'int', except it is not just integers, but characters, that's all, right?
Also, the purpose of putting the calculations inside the cout << instruction would be to shorten the entire program, as well as to remove unnecessary variables, right?
Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.
char holds one ASCII character iirc. If you want a sentence you should use a string. Though you could also use a character array.
char myChar[] = {'H', 'e', 'l', 'l', 'o'};
string myString = "Hello";
|
On June 29 2009 01:35 fusionsdf wrote:Show nested quote +On June 29 2009 00:49 Uligor wrote:On June 29 2009 00:48 konadora wrote:My next question: What data type do I use if I want to use a fraction? I'm currently doing this exercise where I'm supposed to convert inputted Farenheit temperature into centigrade and vice versa, and I need to use the fraction 5/9. float or double. yes at least one of the two numbers must be a float or double, or you must explicitly cast one to a double <static_cast> or integer division will be performed instead.
With the code "(value-32)*5/9" (value being double) the compiler (MSVS08) generated FPU instructions for 5/9, so in this case it was not necessary. However I see your concern because compilers like to precalculate things.
|
are you in uni for a class or something? if you are im a bit confused how you dont understand any of this. If it's a highschool class or something then maybe i get it but some of this stuff you are asking is like first few weeks of learning. I'm just honestly curious not trying to be a dick
|
konadora
Singapore66117 Posts
I'm in high school, started 3 months ago, but I had gotten sick around March (which was the period where my sudden burst in activeness on TL occurred), missing school for a month, after which I failed to revise enough lol.
Not to mention the one month summer break (which ended today) made me just slack all the way.
|
Looks like you are trying to teach yourself programming from scratch without any guidance. That's hard. You should look for a C++ tutorial which explains the basics in an understandable and structured manner. Posing random questions on a very specific problem without quite understanding the answers won't help you much. Especially since those who give advice often look at the problem from a higher level that you don't even need yet. For example, I've seen people talk about compiler settings here, which isn't what you want to know at all and will only confuse you. You won't make it far without knowing basic concepts like control structures, data types, return values etc. So you should try and learn those basics and then come back if any questions remain. Also, it's far easier for a beginner to modify and extend existing code than to write it yourself.
|
On June 29 2009 02:35 Scorch wrote: Looks like you are trying to teach yourself programming from scratch without any guidance. That's hard. You should look for a C++ tutorial which explains the basics in an understandable and structured manner. Posing random questions on a very specific problem without quite understanding the answers won't help you much. Especially since those who give advice often look at the problem from a higher level that you don't even need yet. For example, I've seen people talk about compiler settings here, which isn't what you want to know at all and will only confuse you. You won't make it far without knowing basic concepts like control structures, data types, return values etc. So you should try and learn those basics and then come back if any questions remain. Also, it's far easier for a beginner to modify and extend existing code than to write it yourself. this
|
|
cool site. C++ seems confusing at first but it gets alot easier over time. Certain things I'm trying to learn now are hard to get my head around. Like recursion <_>;
code like this can be hard to get a grip on (atleased for me):
void permute(string current, string rest) { if (rest == "") { cout << current << endl; ++counter; }else{ for ( int i = 0; i < rest.length(); i++ ) { string next = current + rest[i]; string remaining = rest.substr(0, i) + rest.substr(i+1); permute(next, remaining); } } }
the syntax itself is not the difficult aspect, but keeping track of every stack frame and how it unravels is difficult ~_~. There are some great stanford lectures posted up on youtube though! http://www.youtube.com/profile?user=stanforduniversity&view=playlists
Programming Methodology is the beginners course using mostly Java. Programming Abstractions is the intermediate course using C++ Programming Paradigms is the advanced course which I haven't looked at.
|
if you want to learn recursion, learn how to code in lisp or scheme.
|
On June 29 2009 01:41 konadora wrote: Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming.
since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized.
Its really important to stay consistent throughout your code.
|
back to the question void main() and int main() - int main() starts an application which returns an int number ( -2^31..(2^31-1) ) while void main() always returns 0. How this returned value depends on your operating system, on linux you can see that result code e.g. by "echo $?" on bash command line. I think void main() is also not in the recent standard any more, so if you do not know for sure just use "int main()" and don't forget to return a value ( return 0; - you could also write return -1; if an error happend - but its kind of old school )
Btw: This question is rather unimportant - try to write more code - implement some algorithms ( e.g. bread death search in a graph ) - use stl standard library - use external librarys like boost
hf in coding
|
On June 29 2009 05:53 fusionsdf wrote:Show nested quote +On June 29 2009 01:41 konadora wrote: Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming. since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized. Its really important to stay consistent throughout your code.
camel notation ftw. there's also another one that has the type in the variable name, but it's fallen out of favour.
|
konadora
Singapore66117 Posts
On June 29 2009 02:35 Scorch wrote: Looks like you are trying to teach yourself programming from scratch without any guidance. That's hard. You should look for a C++ tutorial which explains the basics in an understandable and structured manner. Posing random questions on a very specific problem without quite understanding the answers won't help you much. Especially since those who give advice often look at the problem from a higher level that you don't even need yet. For example, I've seen people talk about compiler settings here, which isn't what you want to know at all and will only confuse you. You won't make it far without knowing basic concepts like control structures, data types, return values etc. So you should try and learn those basics and then come back if any questions remain. Also, it's far easier for a beginner to modify and extend existing code than to write it yourself. I understand that myself, but I haven't really been taught all the reasoning and concepts, and for my test, I'll have to write a code myself.
Lol I've managed to push my test to wednesday, woot
|
On June 29 2009 08:19 virLudens wrote:Show nested quote +On June 29 2009 05:53 fusionsdf wrote:On June 29 2009 01:41 konadora wrote: Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming. since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized. Its really important to stay consistent throughout your code. camel notation ftw. there's also another one that has the type in the variable name, but it's fallen out of favour.
Hungarian Notation. I've always disliked it
|
On June 29 2009 13:08 fusionsdf wrote:Show nested quote +On June 29 2009 08:19 virLudens wrote:On June 29 2009 05:53 fusionsdf wrote:On June 29 2009 01:41 konadora wrote: Also, if you specify 'C' but the user types in 'c' instead (small C), then does it matter? I recall my teacher saying that caps matter a lot in programming. since nobody answered this: yes, case matter Variable is different from VARIABLE and vArIaBlE. Generally constants are in all CAPS, normal variables are lowercase with either underscores between words like_this_variable or camel case likeThisVariable. Struct and Class names tend to have the first letter capitalized. Its really important to stay consistent throughout your code. camel notation ftw. there's also another one that has the type in the variable name, but it's fallen out of favour. Hungarian Notation. I've always disliked it
Oh cool, I didn't even know it was called the Camel notation. I started with Hungarian Notation, and it's ultra lame
|
Bill307
Canada9103 Posts
I feel like giving a lesson on data type basics. 
8 bits = 1 byte, by the way. If you don't already know this, then repeat this to yourself 10 times, because I will interchange between bits and bytes constantly. E.g. if I say "32 bits" and then "4 bytes" then you need to recognize instantly that I'm talking about the same amount.
When you declare a variable, your compiler will set aside some region in memory (the computer's RAM) for that variable. Whenever you use that variable, you are accessing or modifying that region.
byte and char are both 8-bit (1-byte) variables: they occupy 8 bits in memory. Although they have different uses, in memory they look the same. E.g. the byte 65 and the char 'A' look exactly the same in memory: 65.
int and long are 16-bit and 32-bit variables, respectively. They store #s as integers. They can store both positive and negative integers. In memory, the int 65 might look like this: 0 65. Notice it occupies 2 bytes. Similarly, the long 65 might look like this: 0 0 0 65. If the number is too big to be stored in a single byte, then it spills over into the next byte, allowing you to store larger numbers.
Think of it like base-10 digits. A single digit can store only the numbers 0 to 9. Anything higher than 9 and you need 2 or more digits. Same thing with bytes, except it's base-256. You can store 0-255 in a single byte: anything higher than 255 and you need 2 or more bytes.
Base-10 example, counting from 8 to 12: 0 8 0 9 1 0 1 1 1 2
Base-256 (bytes) example, counting from 254 to 258: 0 254 0 255 1 0 1 1 1 2
If you can't figure out the pattern here, then look up number systems with different bases.
int and long can store negative numbers, too, but that's a lesson for another day. (It's actually pretty simple, if you understand binary and if it's explained correctly.)
If you're wondering what happens when you try to store a number that's too large in a byte, int, or long, then try it for yourself and see what happens (don't worry, it won't break anything). 
float and double are 32-bit and 64-bit variables, respectively. These store numbers in floating point format, which is basically scientific notation. At this point in time, you might as well use doubles. But if you were to make, say, a game, where speed can be important, then you would use only floats in your program.
Pointers, when you start to use them (and die by them), take up 32 bits in memory. They're used to point to some location in memory, like where a variable is stored. Don't even try to learn how to use these until you understand a lot of simpler concepts first. 
Structs and Classes take up varying amounts of memory, depending on what data they contain.
Hopefully now you understand variables a bit better.
|
|
On June 29 2009 16:44 Bill307 wrote: int and long are 16-bit and 32-bit variables, respectively.
The size of int is actually compiler specific; on 32+ bit machines, int is usually 32 bit, which is what I think applies to konadora.
|
Germany2896 Posts
Bill your sizes are usually true on 16 Bit systems. On 32 Bit systems int is usually 32 bit. And the C++ standard promises even less. On 32 Bit VS afaik byte/char=8bit, short=16bit, int/long=32 bit, long long=64 Bit. And of course each of them is available as signed and unsigned.
|
konadora
Singapore66117 Posts
Does it matter if I'm using a 64-bit edition of Vista?
Thanks a lot Bill, understand much clearer now, teacher hardly explained >__<
Thanks Smix
|
Bill307
Canada9103 Posts
Oh, thanks for the correction, guys.
So I guess the corrected version is:
short = 16-bit integer (-32768 to +32767) long = 32-bit integer (approx. -2 billion to +2 billion) int = 16- or 32-bit integer
Bah.
Well, I guess it's safest to assume int is only 16 bits, and use "long" if you need more than that.
|
Germany2896 Posts
From the Stroustrup:
Sizes of C++ objects are expressed in terms of multiples of the size of a char , so by definition the size of a char is 1 . The size of an object or type can be obtained using the sizeof operator. This is what is guaranteed about sizes of fundamental types: 1 = sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) 1 <= sizeof(bool) <= sizeof(long) sizeof(char) <= sizeof(wchar_t) <= sizeof(long) sizeof(float) <= sizeof(double) <= sizeof(long double) sizeof(N) = sizeof(signed N) = sizeof(unsigned N) where N can be char , shortint , int , or longint . In addition, it is guaranteed that a char has at least 8 bits, a short at least 16 bits, and a long at least 32 bits. A char can hold a character of the machine’s character set. Usual are: char=8bit short=16bit int=16 or 32 bit long=32 or 64 bit long long=64 bit
There are also some typedefs with fixed size, but I forgot their names. If I recall correctly there are also some size requirenments for pointers in relation to ints, but I forgot that too. On Win32 it is guaranteed that int,long are 32bit.
|
konadora
Singapore66117 Posts
Bump
I've been doing something called the BMI test, here's my program:
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; a = (w/(h*h)); if (w > 0, h > 0) cout << "Your Body Mass Index is " << a << endl; else cout << "Invalid input." << endl;
if (0 < a < 20, w > 0, h > 0) cout << "You have a low BMI." << endl; else if (20 < a < 25, w > 0, h > 0) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; return 0; }
But the thing is, whenever I put in invalid numbers (-9001 or something), "You have a low BMI." STILL shows. What's the problem?
Will check this when I wake up in the morning, thanks in advance for any help! (going off to sleep;; )
|
#include <iostream> using namespace std;
void main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; a = (w/(h*h)); if (w > 0, h > 0) {cout << "Your Body Mass Index is " << a << endl; if (0 < a < 20, w > 0, h > 0) cout << "You have a low BMI." << endl; else if (20 < a < 25, w > 0, h > 0) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; } else cout << "Invalid input." << endl; }
|
my god, i was good at math in highschool, so i thought i would be good at programming
boy was i wrong
|
Kau
Canada3500 Posts
Don't you need to use && or || for if statements?
|
On July 10 2009 00:59 konadora wrote:Bump I've been doing something called the BMI test, here's my program: Show nested quote +#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; a = (w/(h*h)); if (w > 0, h > 0) cout << "Your Body Mass Index is " << a << endl; else cout << "Invalid input." << endl;
if (0 < a < 20, w > 0, h > 0) cout << "You have a low BMI." << endl; else if (20 < a < 25, w > 0, h > 0) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; return 0; } But the thing is, whenever I put in invalid numbers (-9001 or something), "You have a low BMI." STILL shows. What's the problem? Will check this when I wake up in the morning, thanks in advance for any help! (going off to sleep;; )
This doesn't give you compilation errors?!
if (0 < a < 20, w > 0, h > 0)
You probably meant || or && right...?
|
On July 10 2009 01:36 Kau wrote: Don't you need to use && or || for if statements? yes, yes you do
|
You need to figure out the inequalities... you have 0 < a < 20 and 20 < a < 25, i.e. you don't cover the case where a == 20.
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; // assuming you can't weight 0 kg and have 0 cm height ( h = 0 actually give you division by zero exception if( w <= 0 || h <= 0 ) { cout << "Invalid input." << endl; return 0; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << endl; }
if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl;
return 0; }
|
On July 10 2009 01:17 gokai wrote: my god, i was good at math in highschool, so i thought i would be good at programming
boy was i wrong lol same here, i crawled out of my c programming and mips r2000 class.. phew, never have to program again (hopefully)
good luck kona! i hate programming with a passion so looking at this stuff makes me gag lol.
|
konadora
Singapore66117 Posts
|
On July 10 2009 07:37 konadora wrote: What does || do??
or...
|
konadora
Singapore66117 Posts
Oh lol
Kk thanks
|
|
On July 10 2009 01:47 Cambium wrote: You need to figure out the inequalities... you have 0 < a < 20 and 20 < a < 25, i.e. you don't cover the case where a == 20.
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; // assuming you can't weight 0 kg and have 0 cm height ( h = 0 actually give you division by zero exception if( w <= 0 || h <= 0 ) { cout << "Invalid input." << endl; return 0; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << endl; }
if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl;
return 0; }
ewww. I was always taught multiple return statements like that are frowned upon. to be honest, I'm not exactly sure what's considered acceptable in a professional environment. The code (if someone else is wondering) will still work perfectly, its just a matter of style.
|
Multiple return statements are acceptable in a professional environment.
|
konadora
Singapore66117 Posts
Okay I debugged the thing
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; return 0; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; } if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl;
return 0; }
And still, if I input two negative values, "You have a low BMI." still shows. What's the problem here?
|
that's surprising... did you copy and paste or did you modify your source?
|
konadora
Singapore66117 Posts
Modify
Oh, and happy birthday
|
|
|
konadora
Singapore66117 Posts
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; a = (w/(h*h)); if (w > 0, h > 0) cout << "Your Body Mass Index is " << a << endl; else cout << "Invalid input." << endl;
if (0 < a < 20, w > 0, h > 0) cout << "You have a low BMI." << endl; else if (20 < a < 25, w > 0, h > 0) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; return 0; }
|
Are you still using commas in the 'if' statements? If you are then that's a problem. You have to use && for AND, || for OR
I guess you maybe just pasted the wrong source?
|
konadora
Singapore66117 Posts
Nope. The modified one is the one few posts above
|
Ok. I got confused because your last post has the commas in it.
|
What's your OS and what IDE/compiler are you using?
I'm amazed at its ability to interpret equalities and inequalities...
The problem with your code is that you don't terminate when you detected invalid inputs. The program continues to run and since two negatives give you a positive, you get "You have a low BMI".
After you terminate, you no longer need to check w > 0 and h > 0, as you have already done so.
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; a = (w/(h*h)); if (w > 0, h > 0) cout << "Your Body Mass Index is " << a << endl; else { cout << "Invalid input." << endl; return 0; }
if (0 < a < 20, w > 0, h > 0) cout << "You have a low BMI." << endl; else if (20 < a < 25, w > 0, h > 0) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; return 0; }
|
konadora
Singapore66117 Posts
Ooooh
I was wondering but, it's okay to have many 'return 0; ' statements?
|
Now Cambium is modifying the source with the commas too. Hrmm, perhaps I'm still confused as to what your latest source is.
|
I'm confused. Which source are you running?
There is no way you get anything beyond "invalid input" if you ran the code below...
if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; return 0; }
catches any negative inputs.
+ Show Spoiler + #include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; return 0; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; } if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl;
return 0; }
|
It's sort of ok. You can do it, but for beginning programming it's usually much easier to keep a single return for a function (main in this case).
|
Yes, it's okay to have multiple return statements... but this is better structurally, because your first if/else statement doesn't make too much sense.
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; } return 0; }
|
konadora
Singapore66117 Posts
OS = Vista 64-bit Compiler = Visual C++ 2008 Express Edition
I'm using this one
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; return 0; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; } if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl;
return 0; }
The one I posted after that was the original before I modified it
|
Also something you should get into a habit of doing is using proper variable names. You may not care about this now but it will help in the future. It also helps others (such as us trying to help you) read your code.
So "a" is body mass index you might call the variable "bmi" instead. double bmi;
w and h are ok for variable names, but they could be better. double weightKG; double heightM;
Or something similar.
|
Just in case you don't see it... here it is again...
On July 10 2009 11:26 Cambium wrote:Yes, it's okay to have multiple return statements... but this is better structurally, because your first if/else statement doesn't make too much sense. Show nested quote +
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; } return 0; }
|
konadora
Singapore66117 Posts
Cambium, I've the EXACT same program and yet, when I input a value like " -1023123", the 'You have a low BMI." message appears >__<
|
I'm just checking things through notepad but Cambium's code looks good. Seems very strange that it's not working for you konadora so I'm downloading VS c++ express right now.
|
Ok I just ran it and I get the "Invalid input." as expected. I'm not sure what you might be doing konadora.
Maybe you are somehow running an old executable. Try a clean and build.
|
konadora
Singapore66117 Posts
Oh okay, nvm I found the error (different .cpp running -____- )
Sorry about that!
|
lol that's always fun. I FIXED IT, WHY ISN'T IT WORKING?!!
|
On July 10 2009 12:20 SonuvBob wrote: lol that's always fun. I FIXED IT, WHY ISN'T IT WORKING?!!
god. so much time wasted because of that and you can't even feel all that happy when you fix it.
"THIS held me up for 2 hours? THIS?!!?"
|
konadora
Singapore66117 Posts
yeah wtf man lol
Gotta continue revising
|
#include <iostream> using namespace std;
int main() { double w, h; double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; // } why are you closing the if here
if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; } // closeit here return 0; }
look the correction and the comentary in bold.
there is something weird in the first scope too...
I now think that something... it seems that you believe that return will end the program. Thats not gonna happen, return 0; will jump out of the scope, not from the program. And that first return should be diferent to 0, 0 is NO ERROR. Using stdlib.h (#include <stdlib.h>) you could use exit() function, like this "exit(1);" that will end the program and return 1 from main to std out
The thing is "a" cannot be empty, when you reserve the memory it has some value. So it will mostly have any value different to 1..24, then you always will see at std out "You have exceeded..."
Try this as an example:
#include <iostream> using namespace std;
int main() {
int a; double b; char c;
cout << a << b << c;
return 0;
}
|
a is defined as being w * h before it is actually used for anything. Since w and h are both initialized by the keyboard (and assuming valid keyboard input) a does not have to be given an initial value (neither do w or h since they are given an initial value before they are used.
To simplify it,
int a = 0;
is just as valid as
int a; //a's value is ???? a = 0;
As long as the assignment of 0 occurs before the variable is used, its fine.
As for exit, while you are correct it will work, its been out of favor and frowned upon (in both academic and most professional environments) for a long time. Because main is a function, when it returns, the function will end and it will return to the C++ environment, which will then end as a consequence. Having multiple return statements in main() will work just like it would in any function, although I disagree with it from a stylistic point of view.
here's a pretty cool discussion of multiple returns in C/C++: http://bytes.com/groups/c/617841-multiple-returns-functions
|
konadora
Singapore66117 Posts
coltrane's post is headache >__<
thanks fusionsdf
so I can just say double a = (w/(h*h)); ?
|
yes, as long as:
1) a isnt used any point before that line (since by saying double a you are declaring a) 2) w and h have already been declared and given values before that line.
As a matter of practice, its considered best to put all your variable declarations in one spot right at the top.
so while both
+ Show Spoiler [#1] +#include <iostream> using namespace std;
int main() { double w, h;
double a; //declaring a further on, so this declaration must be removed. cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; } else { double a = (w/(h*h)); //declaring here. This is still valid and will execute properly. cout << "Your Body Mass Index is " << a << "." << endl; if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; } return 0; }
+ Show Spoiler [#2] +#include <iostream> using namespace std;
int main() { double w, h; //all variables are declared in the same spot at the top of the function double a; cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl; if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; } return 0; }
are valid, #2 is considered better from a style point of view (both will execute exactly the same). Since you have to deal with potentially other people going through your code, or you taking a break, forgetting about this program and trying to understand what you were doing 3 month or even 3 years from now, you really want to make sure you are aware of what is considered good style and follow it whenever it makes sense to you.
Extra stuff
I want to add 2 more things that aren't obvious:
1) In Cambium's code he has: if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl;
For single line statements you do not need braces. That code is equivalent to:
if ( a > 0 && a < 20 ) { cout << "You have a low BMI." << endl; } else if ( a > 20 && a < 25 ) { cout << "You are within the healthy BMI range. Congratulations!" << endl; } else { cout << "You have exceeded the healthy BMI range." << endl; }
Note that if there is more than one line, you cant omit the braces and still have it work. This will NOT do what is expected:
if ( a > 0 && a < 20 ) //line 1 cout << "You have a low BMI." << endl; //line 2 cout << "good bye!." << endl; //line 3
and will execute line 2 only if line 1 evaluates true and will execute line 3 in every case. When its more than one line, use braces. For multiple single line if else statements, omitting the braces is more often used, but check with your teacher to make sure thats the style she prefers.
2) the second point is that while
int a = 0;
and
int a; a = 0;
is true for pretty much every primitive type (double, char, int, float), this does not work for c-strings
char c = "hello";
is valid.
char c; c = "hello";
won't work (instead you would have to use a built in function)... this might not be an issue for you right now (its certainly not important for this program), but if you ever have a problem with c-strings like that, at least now you've seen it pointed out.
|
konadora
Singapore66117 Posts
Ah I see, clear about this now, thanks!!
|
|
On July 10 2009 23:53 konadora wrote: coltrane's post is headache >__<
thanks fusionsdf
so I can just say double a = (w/(h*h)); ?
first... why???
and second... no, you cant unless you define a after w and h. And if you do so and then you input 2 wrong values a will have the first value from its definition.
|
konadora
Singapore66117 Posts
Because I don't understand what you're talking about at all
I'm fairly new to C++ so...
|
okok;
copypaste this and compile it:
#include <iostream> using namespace std;
int main() {
int a; double b; char c;
cout << a << b << c;
return 0;
}
When you run that shit you will realize that:
Variables always have a value, even when you dont asign any variable to it.
So, a good manner thing is to put some value in a variable like the a in your program WHY? because you are ALWAYS running a multiple selection test on it, but you are NOT ALWAYS assigning a value to it. A good form to do that is changing
double a;
for the sentence
double a(0);
^ thats a constructor, is a function over a variable. It basically says something like "assign 0 to a variable" at the very moment that you declare it as variable.
I will rewrite your code.
+ Show Spoiler + #include <iostream> using namespace std;
int main() { double w, h; double a(0); cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; //this line is a comment. The compiler will skip it. ok, you asked for //2 values, if they dont fit the condition then we end just here, // and a is 0 right now. } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl;
//a has a new valid value. And then we ask:
if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; // i suppose you understand why we dont need brackets {} in this if } // if the inputed values are useless to us, then we are here. return 0; }
|
If you are going to link C++ FAQ Lite, at least link C++ FQA Lite
|
On July 12 2009 05:37 coltrane wrote:okok; copypaste this and compile it: Show nested quote +#include <iostream> using namespace std;
int main() {
int a; double b; char c;
cout << a << b << c;
return 0;
} When you run that shit you will realize that: Variables always have a value, even when you dont asign any variable to it. So, a good manner thing is to put some value in a variable like the a in your program WHY? because you are ALWAYS running a multiple selection test on it, but you are NOT ALWAYS assigning a value to it. A good form to do that is changing double a; for the sentence double a(0); ^ thats a constructor, is a function over a variable. It basically says something like "assign 0 to a variable" at the very moment that you declare it as variable. I will rewrite your code. + Show Spoiler + #include <iostream> using namespace std;
int main() { double w, h; double a(0); cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; //this line is a comment. The compiler will skip it. ok, you asked for //2 values, if they dont fit the condition then we end just here, // and a is 0 right now. } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl;
//a has a new valid value. And then we ask:
if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; // i suppose you understand why we dont need brackets {} in this if } // if the inputed values are useless to us, then we are here. return 0; }
honestly I think that's overkill. As long as the programmer is smart enough to assign a value to the variable at some point before use (and hopefully a sanity check), there is no need to have every variable declaration include an assignment.
int a; double b; char c;
a = 0; b = 0.0; c = cin.get();
cout << a << b << c;
return 0;
There is no point declaring c with an initial value when you are just going to be getting it from the keyboard immediately after anyways.
|
On July 12 2009 16:01 fusionsdf wrote:Show nested quote +On July 12 2009 05:37 coltrane wrote:okok; copypaste this and compile it: #include <iostream> using namespace std;
int main() {
int a; double b; char c;
cout << a << b << c;
return 0;
} When you run that shit you will realize that: Variables always have a value, even when you dont asign any variable to it. So, a good manner thing is to put some value in a variable like the a in your program WHY? because you are ALWAYS running a multiple selection test on it, but you are NOT ALWAYS assigning a value to it. A good form to do that is changing double a; for the sentence double a(0); ^ thats a constructor, is a function over a variable. It basically says something like "assign 0 to a variable" at the very moment that you declare it as variable. I will rewrite your code. + Show Spoiler + #include <iostream> using namespace std;
int main() { double w, h; double a(0); cout << "Please enter your weight (in KG) and height (in meters)." << endl; cin >> w >> h; if (w <= 0 || h <= 0){ cout << "Invalid input." << endl; //this line is a comment. The compiler will skip it. ok, you asked for //2 values, if they dont fit the condition then we end just here, // and a is 0 right now. } else { a = (w/(h*h)); cout << "Your Body Mass Index is " << a << "." << endl;
//a has a new valid value. And then we ask:
if ( a > 0 && a < 20 ) cout << "You have a low BMI." << endl; else if ( a > 20 && a < 25 ) cout << "You are within the healthy BMI range. Congratulations!" << endl; else cout << "You have exceeded the healthy BMI range." << endl; // i suppose you understand why we dont need brackets {} in this if } // if the inputed values are useless to us, then we are here. return 0; }
honestly I think that's overkill. As long as the programmer is smart enough to assign a value to the variable at some point before use (and hopefully a sanity check), there is no need to have every variable declaration include an assignment. int a; double b; char c; a = 0; b = 0.0; c = cin.get(); cout << a << b << c; return 0; There is no point declaring c with an initial value when you are just going to be getting it from the keyboard immediately after anyways.
yes, but is a good thing to understand that a variable will have some value always. Anyway i just said him to assign a value to a variable, not to every variable...
|
|
|
|