• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 18:01
CEST 00:01
KST 07:01
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
Maestros of the Game: Week 1/Play-in Preview9[ASL20] Ro24 Preview Pt2: Take-Off7[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4Team Liquid Map Contest #21 - Presented by Monster Energy9
Community News
Weekly Cups (August 25-31): Clem's Last Straw?32Weekly Cups (Aug 18-24): herO dethrones MaxPax6Maestros of The Game—$20k event w/ live finals in Paris46Weekly Cups (Aug 11-17): MaxPax triples again!15Weekly Cups (Aug 4-10): MaxPax wins a triple6
StarCraft 2
General
Speculation of future Wardii series Weekly Cups (August 25-31): Clem's Last Straw? Heaven's Balance Suggestions (roast me) Geoff 'iNcontroL' Robinson has passed away #1: Maru - Greatest Players of All Time
Tourneys
LiuLi Cup - September 2025 Tournaments Sea Duckling Open (Global, Bronze-Diamond) Sparkling Tuna Cup - Weekly Open Tournament Maestros of The Game—$20k event w/ live finals in Paris Monday Nights Weeklies
Strategy
Custom Maps
External Content
Mutation # 489 Bannable Offense Mutation # 488 What Goes Around Mutation # 487 Think Fast Mutation # 486 Watch the Skies
Brood War
General
ASL20 General Discussion Starcraft at lower levels TvP BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion Victoria gamers
Tourneys
[Megathread] Daily Proleagues Is there English video for group selection for ASL [ASL20] Ro24 Group F [IPSL] CSLAN Review and CSLPRO Reimagined!
Strategy
Simple Questions, Simple Answers Muta micro map competition Fighting Spirit mining rates [G] Mineral Boosting
Other Games
General Games
Stormgate/Frost Giant Megathread General RTS Discussion Thread Warcraft III: The Frozen Throne Nintendo Switch Thread Mechabellum
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine Canadian Politics Mega-thread YouTube Thread
Fan Clubs
The Happy Fan Club!
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece [\m/] Heavy Metal Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread High temperatures on bridge(s) Gtx660 graphics card replacement
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
A very expensive lesson on ma…
Garnet
hello world
radishsoup
Lemme tell you a thing o…
JoinTheRain
How Culture and Conflict Imp…
TrAiDoS
RTS Design in Hypercoven
a11
Evil Gacha Games and the…
ffswowsucks
INDEPENDIENTE LA CTM
XenOsky
Customize Sidebar...

Website Feedback

Closed Threads



Active: 742 users

C++ revision help! - Page 6

Blogs > konadora
Post a Reply
Prev 1 4 5 6 7 Next All
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:28 GMT
#101
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.
twitter: @terrancem
Cambium
Profile Blog Joined June 2004
United States16368 Posts
July 10 2009 02:34 GMT
#102
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;
}

When you want something, all the universe conspires in helping you to achieve it.
konadora *
Profile Blog Joined February 2009
Singapore66201 Posts
July 10 2009 02:36 GMT
#103
Cambium, I've the EXACT same program and yet, when I input a value like " -1023123", the 'You have a low BMI." message appears >__<
POGGERS
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
July 10 2009 02:39 GMT
#104
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.
twitter: @terrancem
GogoKodo
Profile Blog Joined April 2003
Canada1785 Posts
Last Edited: 2009-07-10 02:53:03
July 10 2009 02:52 GMT
#105
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.
twitter: @terrancem
konadora *
Profile Blog Joined February 2009
Singapore66201 Posts
July 10 2009 03:06 GMT
#106
Oh okay, nvm I found the error (different .cpp running -____- )

Sorry about that!
POGGERS
SonuvBob
Profile Blog Joined October 2006
Aiur21549 Posts
July 10 2009 03:20 GMT
#107
lol that's always fun. I FIXED IT, WHY ISN'T IT WORKING?!!
Administrator
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
July 10 2009 03:22 GMT
#108
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?!!?"
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
konadora *
Profile Blog Joined February 2009
Singapore66201 Posts
July 10 2009 03:26 GMT
#109
yeah wtf man lol

Gotta continue revising
POGGERS
coltrane
Profile Blog Joined June 2008
Chile988 Posts
Last Edited: 2009-07-10 09:09:49
July 10 2009 09:08 GMT
#110
#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;

}
Jävla skit
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
July 10 2009 14:43 GMT
#111
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
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
konadora *
Profile Blog Joined February 2009
Singapore66201 Posts
July 10 2009 14:53 GMT
#112
coltrane's post is headache >__<

thanks fusionsdf

so I can just say double a = (w/(h*h)); ?
POGGERS
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
Last Edited: 2009-07-10 15:23:13
July 10 2009 15:15 GMT
#113
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.
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
konadora *
Profile Blog Joined February 2009
Singapore66201 Posts
July 10 2009 15:17 GMT
#114
Ah I see, clear about this now, thanks!!
POGGERS
yh8c4
Profile Blog Joined July 2009
108 Posts
July 10 2009 16:09 GMT
#115
some recommendations:

put your code on http://codepad.org. saves the formatting, has syntax coloring, and can even compile and run the code. i put your code to http://codepad.org/Yn2ulRxd and added some minor corrections (marked by comments).

good c++ resources:
http://www.parashift.com/c -faq-lite/
http://www.cplusplus.com/
channel ##c++ on irc.freenode.net

coltrane
Profile Blog Joined June 2008
Chile988 Posts
July 11 2009 09:22 GMT
#116
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.




Jävla skit
konadora *
Profile Blog Joined February 2009
Singapore66201 Posts
July 11 2009 09:26 GMT
#117
Because I don't understand what you're talking about at all

I'm fairly new to C++ so...
POGGERS
coltrane
Profile Blog Joined June 2008
Chile988 Posts
Last Edited: 2009-07-11 20:43:27
July 11 2009 20:37 GMT
#118
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;
}

Jävla skit
Jovan
Profile Joined August 2006
Canada65 Posts
July 11 2009 21:13 GMT
#119
On July 11 2009 01:09 yh8c4 wrote:
some recommendations:

put your code on http://codepad.org. saves the formatting, has syntax coloring, and can even compile and run the code. i put your code to http://codepad.org/Yn2ulRxd and added some minor corrections (marked by comments).

good c++ resources:
http://www.parashift.com/c -faq-lite/
http://www.cplusplus.com/
channel ##c++ on irc.freenode.net



If you are going to link C++ FAQ Lite, at least link C++ FQA Lite
fusionsdf
Profile Blog Joined June 2006
Canada15390 Posts
July 12 2009 07:01 GMT
#120
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.
SKT_Best: "I actually chose Protoss because it was so hard for me to defeat Protoss as a Terran. When I first started Brood War, my main race was Terran."
Prev 1 4 5 6 7 Next All
Please log in or register to reply.
Live Events Refresh
Next event in 1h 59m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
JuggernautJason79
StarCraft: Brood War
Britney 19530
Dewaltoss 108
Aegong 41
sSak 40
NaDa 22
yabsab 7
Counter-Strike
Stewie2K737
Foxcn303
Super Smash Bros
Liquid`Ken21
Heroes of the Storm
Liquid`Hasu492
Other Games
summit1g3062
Grubby2345
FrodaN1368
C9.Mang0161
Trikslyr130
Livibee82
Mew2King69
Nathanias33
Chillindude23
ViBE22
rGuardiaN20
Kaelaris9
Organizations
Other Games
BasetradeTV12
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 20 non-featured ]
StarCraft 2
• davetesta74
• StrangeGG 31
• LaughNgamezSOOP
• sooper7s
• AfreecaTV YouTube
• intothetv
• Migwel
• Kozan
• IndyKCrew
StarCraft: Brood War
• Pr0nogo 4
• ZZZeroYoutube
• STPLYoutube
• BSLYoutube
Dota 2
• masondota22322
League of Legends
• Doublelift5328
• TFBlade360
• HappyZerGling72
Counter-Strike
• imaqtpie1111
• Shiphtur196
Other Games
• Scarra603
Upcoming Events
Replay Cast
1h 59m
The PondCast
11h 59m
RSL Revival
11h 59m
Maru vs SHIN
MaNa vs MaxPax
Maestros of the Game
18h 59m
Classic vs TriGGeR
Reynor vs SHIN
OSC
1d 4h
MaNa vs SHIN
SKillous vs ShoWTimE
Bunny vs TBD
Cham vs TBD
RSL Revival
1d 11h
Reynor vs Astrea
Classic vs sOs
Maestros of the Game
1d 18h
Serral vs Ryung
ByuN vs Zoun
BSL Team Wars
1d 20h
Team Bonyth vs Team Dewalt
CranKy Ducklings
2 days
RSL Revival
2 days
GuMiho vs Cham
ByuN vs TriGGeR
[ Show More ]
Cosmonarchy
2 days
TriGGeR vs YoungYakov
YoungYakov vs HonMonO
HonMonO vs TriGGeR
Maestros of the Game
2 days
Solar vs Bunny
Clem vs Rogue
[BSL 2025] Weekly
2 days
RSL Revival
3 days
Cure vs Bunny
Creator vs Zoun
Maestros of the Game
3 days
Maru vs Lambo
herO vs ShoWTimE
BSL Team Wars
3 days
Team Hawk vs Team Sziky
Sparkling Tuna Cup
4 days
Monday Night Weeklies
4 days
Liquipedia Results

Completed

CSL Season 18: Qualifier 2
SEL Season 2 Championship
HCC Europe

Ongoing

Copa Latinoamericana 4
BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Qualifiers
ASL Season 20
CSL 2025 AUTUMN (S18)
Maestros of the Game
Sisters' Call Cup
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025

Upcoming

LASL Season 20
2025 Chongqing Offline CUP
BSL Season 21
BSL 21 Team A
Chzzk MurlocKing SC1 vs SC2 Cup #2
RSL Revival: Season 2
EC S1
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
MESA Nomadic Masters Fall
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.