Avatar of kelvin muriithi
kelvin muriithi
 asked on

please help me convert this python code to C++ code

#this program calculates the area of a right triangle                                                                 #ask for input
b=input('Enter the triangle base:')
h=input('Enter the triangle height:')

#Calculate and print area
Area=(b*h)/2
Print '\n The base is '+str(b) + 'units'
Print 'The height is   'str(h) + 'units'
Print '\n The area is 'str(area + 'units
C++Python

Avatar of undefined
Last Comment
MURUGESAN N

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
sarabande

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
MURUGESAN N

Updated the code.
#ifdef CYGWIN_NT
	#include <iostream>
	using namespace std;
#elif NEXT_PLATFORM
	#include <iostream.h>
#else
	#include <iostream>
#endif
#include <sstream>
#include <string>
int main()
{
	int b = 0; // Base value of triangle
	int h = 0; // Height of triangle
	std::string in = "";
	while ( true)
	{
		if ( 0 == b)
		{
			std::cout << "Enter:\nquit\nto exit this program.\nEnter base value for triangle: ";
			#ifdef CYGWIN_NT
				getline(cin, in);
			#else
				std::getline(in);
			#endif
			if ( "quit" == in)
			{
				return 0;
			}
			std::istringstream isb(in);
			if (!(isb >> b))
			{
				std::cout << "Provide number for base value of triangle\n";
				continue;
			}
		}
		std::cout << "Enter:\nquit\nto exit this program.\nEnter the triangle height: ";
		#ifdef CYGWIN_NT
			getline(cin, in);
		#else
			std::getline(in);
		#endif
		if ( "quit" == in)
		{
			return 0;
		}
		std::istringstream ish(in);
		if (!(ish >> h))
		{
			std::cout << "Provide number for height value of triangle\n";
			continue;
		}
		break;
	}
	//Calculate and print area
	double Area = ( b * h) / 2.0;
	std::cout << "Base   : " << b <<" units\n";
	std::cout << "Height : " << h << " units\n";
	std::cout << "Area   : " << Area << " units\n";
	return 0;
}
/*
# DD/MMM/YYYY Name           Comment
# 19/Apr/2017 Author         Reason for updates
1. Compiled the code using cygwin, hence added using namespace std;
2. Always initialize a variable while defining that.
	Replace:
			std::string in;
	With:
			std::string in = "";
3.	Replace:
		std::cout << "\nEnter the triangle base: ";
	With:
		std::cout << "Enter the triangle base: ";
	Like the same written all expected cout statements.
4. Better to use:
		if (0 == b)
	instead of
		if (b == 0)
	since by mistake programmer might write
		if (b = 0)
	for handling assignment inside conditional checking.
	which will assign zero to b.
5.	Replace:
		std::getline(in);
	With:
			#ifdef CYGWIN_NT
				getline(cin, in);
			#else
				std::getline(in);
			#endif
		due to cygwin compilation.
6. Added { } at if conditions for easy readability.
7.	Replace:
		if (in == "quit")
	With:
		if ( "quit" == in)
	for handling assignment inside conditional checking.
8. Compilation at cygwin:
	/usr/bin/g++.exe -g -Wall test.cpp -DCYGWIN_NT
9.	Replace:
		std::cout << "\nThe area is " << area << "units" << std::endl;
	With:
		std::cout << "Area   : " << Area << " units\n";
	to use Area variable.
10.	Replace:
		int Area = (b*h)/2;
	With:
		double Area = ( b * h) / 2.0;
11. Compilation at cygwin:
	/usr/bin/g++.exe -g -Wall test.cpp -DCYGWIN_NT -o ./a.out
12. Sample output at cygwin:
$ ./a.out
Enter:
quit
to exit this program.
Enter base value for triangle: 7
Enter:
quit
to exit this program.
Enter the triangle height: 3
Base   : 7 units
Height : 3 units
Area   : 10.5 units
13. Same program can also be updated to change required output format.
*/

Open in new window

sarabande

actually the updates made are not needed (also not by cygwin) and there is no requirement for cygwin in the op.

1. Compiled the code using cygwin, hence added using namespace std;
a using clause generally can be omitted when using the namespace prefix. also you could use std:: regardless whether a 'using namespace std;' was given or not.

 
2. Always initialize a variable while defining that.
      Replace:
                  std::string in;
      With:
                  std::string in = "";

std::string is a class with a default constructor which does all necessary initialization. extra initialization of a class with a default constructor can be contra-productive and error-prone if the default constructor is different to the constructor used with the initializing argument.  

3.      Replace:
            std::cout << "\nEnter the triangle base: ";
      With:
            std::cout << "Enter the triangle base: ";
      Like the same written all expected cout statements.
the first output statements at the console always should begin with at least one line-feed because otherwise the output could begin anywhere in the middle of the console.

4. Better to use:
            if (0 == b)
      instead of
            if (b == 0)
      since by mistake programmer might write
            if (b = 0)
      for handling assignment inside conditional checking.
      which will assign zero to b.
no, the (b == 0) is much better readable than (0 == b). you will get a warning from the compiler if you write
if (b = 0)

Open in new window

.

5.      Replace:
            std::getline(in);
      With:
                  #ifdef CYGWIN_NT
                        getline(cin, in);
                  #else
                        std::getline(in);
                  #endif
            due to cygwin compilation.
std::getline(in) is a typing error. the correct Statement is
std::getline(cin, in);

Open in new window


what will work for all c++ Compilers including cygwin.

6. Added { } at if conditions for easy readability.
i don't use {} blocks when the block contains only one return, break, or continue statement. that is to improve readability as you could see more significant statements. you may have a different opinion what is ok..

7.      Replace:
            if (in == "quit")
      With:
            if ( "quit" == in)
      for handling assignment inside conditional checking.
the first is better readable. see above.

9.      Replace:
            std::cout << "\nThe area is " << area << "units" << std::endl;
      With:
            std::cout << "Area   : " << Area << " units\n";
      to use Area variable.
why?

10.	Replace:
		int Area = (b*h)/2;
	With:
		double Area = ( b * h) / 2.0;

Open in new window

that could be good if b and h are integers  with an odd number. if the original code (Python) can handle integers and doubles without explicit types, i would suggest to use double for h, b, and Area.

Murugusan, you made a lot of changes to my code sample without adding any substantial code and most of your "corrections"  is unneeded or even wrong (for example when including iostream.h). note, code  posted by experts mostly are code snippets which require the questioner to add comments and validations theirselves and even correct typing errors which might happen when the code is typed here as a comment without help of the compiler.

I don't think that your comment can be called a solution.

Sara
sarabande

as already told, the code posted was a code snippet where the Author may give feedback and ask for more details or further help.
 
other experts may check the code and and post corrections if the were sure that there are errors or missing or wrong functionality. but they definitively were not asked to make some kind of code review and post the same code "purified" as a new solution, especially as the suggested changes are neither necessary nor give any help to understand the original code.
 
1. >> there is no requirement for cygwin
 Written the code for optimization at all platforms.
you didn't try it for "all platforms" but only for one, while the code i posted was pure c++ and actually would compile at each platform with a compiler since c++ standard (1998). you added preprocessor statements
 
#ifdef CYGWIN_NT
 #include <iostream>
 using namespace std;
#elif NEXT_PLATFORM
 #include <iostream.h>
#else
 #include <iostream>
#endif

Open in new window


which do not make any sense. if the macro CYGWIN_NT was defined, you add a 'using clause' for the namespace 'std' which was not needed, as all namespace objects correctly were defined with the std:: prefix. i think you did this, because my code had a wrong statement 'std::getline(in);' where you got a compiler error and where you thought, the missing using clause was needed in cygwin and would solve the issue. it actually does compile but not because of omitting the std:: prefix but because you correctly added 'cin' as first argument what was the mistake i made in my first code. the statement
 
std::getline(cin, in);

Open in new window


would have solved the issue without any preprocessor macros and this correction would have been a valuable contribution from your side to the posted code. instead you made a mess out of the code snippet which only would build with your environment and would not build at any other platform. worse, you added a preprocessor option with macro NEXT_PLATFORM which includes iostream.h. this is  a header used for i/o streams before c++ standard. it is obsolete for all c++ compilers i know from 1998 or later. it is not supported by any c++ compiler younger than 2006. so, if would have tried to compile with the macro NEXT_PLATFORM you have got an error that iostream.h cannot be found. last option is to neither have defined NEXT_PLATFORM  nor CYGWIN_NT. with that you have used my code not defining a using clause and compiling the erronuous statement with std::getline and the missing cin argument. so, your code is only compiling if the macro CYGWIN_NT is given for build but it would also compile at all other c++ platforms although you didn't have been aware of.
 
2. >> std::string in = "";
 A good programmer need to initialize the variable where ever it is defined.
you are wrong. while this statement is true for all plain c types, it generally doesn't make sense if you want to create an empty  class or struct object which has a valid default constructor. defining code which is redundant or not needed is not good programming but blows your code up and makes it badly readable.  note, the compiler would generate a default constructor, a copy constructor and a default assignment operator for your class. if your class only has class members and no plain c types as members, you don't need to write code for all these. that makes your code lean and easy to maintain.
 
3. >> no, the (b == 0) is much better readable than (0 == b). you will get a warning from the compiler if you write
 Usually here goes related to development at all development projects
 1. Initially written by old team members
 Current team members need to handle old errors
 Such kind of errors used to happen.
as told, you may have your code guide lines and i have mine. but you must not spoil another thread with those issues as they are off-topic.  if you want to discuss these, you can ask your own question, and i am sure there are many experienced c++ programmers with an expertise of multiple decades which would participate.
 
5. >> double Area = ( b * h) / 2.0;
handled the output to display when odd numbers are given input.

i found the following
 
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the ``narrower'' type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule.2.6 The constructors int(), long(), float(), and complex() can be used to produce numbers of a specific type.
that means that you are right by making Area a double. so point 5 would have been valuable if posted as an addition to my comment.

again, i can't see any value in your posts.

Sara
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
MURUGESAN N

Yesterday's comment:
>> Update and close the query as per the requirement.