• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 21:10
CET 03:10
KST 11:10
  • 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
TL.net Map Contest #21: Winners11Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13TL.net Map Contest #21: Voting12[ASL20] Ro4 Preview: Descent11
Community News
Weekly Cups (Nov 3-9): Clem Conquers in Canada0SC: Evo Complete - Ranked Ladder OPEN ALPHA2StarCraft, SC2, HotS, WC3, Returning to Blizzcon!45$5,000+ WardiTV 2025 Championship7[BSL21] RO32 Group Stage4
StarCraft 2
General
Craziest Micro Moments Of All Time? SC: Evo Complete - Ranked Ladder OPEN ALPHA Mech is the composition that needs teleportation t Weekly Cups (Nov 3-9): Clem Conquers in Canada RotterdaM "Serral is the GOAT, and it's not close"
Tourneys
Tenacious Turtle Tussle Constellation Cup - Main Event - Stellar Fest Sparkling Tuna Cup - Weekly Open Tournament $5,000+ WardiTV 2025 Championship Merivale 8 Open - LAN - Stellar Fest
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 499 Chilling Adaptation Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection
Brood War
General
BW General Discussion FlaSh on: Biggest Problem With SnOw's Playstyle BGH Auto Balance -> http://bghmmr.eu/ [ASL20] Ask the mapmakers — Drop your questions Where's CardinalAllin/Jukado the mapmaker?
Tourneys
[Megathread] Daily Proleagues [ASL20] Grand Finals [BSL21] RO32 Group A - Saturday 21:00 CET [BSL21] RO32 Group B - Sunday 21:00 CET
Strategy
Current Meta PvZ map balance How to stay on top of macro? Soma's 9 hatch build from ASL Game 2
Other Games
General Games
Nintendo Switch Thread Stormgate/Frost Giant Megathread Should offensive tower rushing be viable in RTS games? Path of Exile Dawn of War IV
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
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread US Politics Mega-thread Canadian Politics Mega-thread The Games Industry And ATVI
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Learning my new SC2 hotkey…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Our Last Hope in th…
KrillinFromwales
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1566 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
Singapore66357 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
Singapore66357 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
Singapore66357 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
Singapore66357 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
Singapore66357 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
Singapore66357 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
Replay Cast
23:00
Enki Epic Series #6 | LiuLi Cup #47
CranKy Ducklings178
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
SpeCial 140
Nathanias 64
Nina 40
StarCraft: Brood War
Shuttle 904
Artosis 688
NaDa 32
Dota 2
monkeys_forever430
League of Legends
JimRising 324
Counter-Strike
fl0m1508
Super Smash Bros
hungrybox346
Other Games
summit1g12554
shahzam574
Maynarde139
C9.Mang0122
Organizations
Other Games
gamesdonequick1108
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 13 non-featured ]
StarCraft 2
• davetesta34
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• masondota21786
Other Games
• Scarra1306
Upcoming Events
WardiTV Korean Royale
9h 50m
OSC
14h 50m
Replay Cast
20h 50m
Replay Cast
1d 6h
Kung Fu Cup
1d 9h
Classic vs Solar
herO vs Cure
Reynor vs GuMiho
ByuN vs ShoWTimE
Tenacious Turtle Tussle
1d 20h
The PondCast
2 days
RSL Revival
2 days
Solar vs Zoun
MaxPax vs Bunny
Kung Fu Cup
2 days
WardiTV Korean Royale
2 days
[ Show More ]
PiGosaur Monday
2 days
RSL Revival
3 days
Classic vs Creator
Cure vs TriGGeR
Kung Fu Cup
3 days
CranKy Ducklings
4 days
RSL Revival
4 days
herO vs Gerald
ByuN vs SHIN
Kung Fu Cup
4 days
BSL 21
4 days
Tarson vs Julia
Doodle vs OldBoy
eOnzErG vs WolFix
StRyKeR vs Aeternum
Sparkling Tuna Cup
5 days
RSL Revival
5 days
Reynor vs sOs
Maru vs Ryung
Kung Fu Cup
5 days
WardiTV Korean Royale
5 days
BSL 21
5 days
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
Wardi Open
6 days
Monday Night Weeklies
6 days
Liquipedia Results

Completed

Proleague 2025-11-07
Stellar Fest: Constellation Cup
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual

Upcoming

SLON Tour Season 2
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
RSL Revival: Season 3
META Madness #9
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals 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.