my solution to find area of a triangle when base and height is given(the question specifically asked to also use float typcasting):
#include <iostream>
using namespace std;
int area()
{
int b=7,h=5;
float area;
area=(float)b*h/2;
return area;//Write a expression to find Area as float using typecasting
}
correct solution:
#include<iostream>
using namespace std;
void area()
{
int b=7,h=5;
float area;
area=(float)b*h/2;
cout<<area;
}
what's wrong with my code?
By itself I would say nothing much.
When you want to calculate a floating point number, makes sure ALL you values are floating point. Eg. not 2 but 2.0f
Casting in C++ is usually done with static_cast (or one of the other cast functions). The notation you use is more "C" style type casting
I am not a big fan of using, "using namespace" specially in larger projects. In source it can be ok, NEVER do this in header files though.
I would code it like this:
float calculate_triangle_area(const int b, const int h) noexcept
{
float area = static_cast<float>(b) * static_cast<float>(h) / 2.0f;
return area;
}
std::cout << calculate_triangle_area(5,7);
Some more notes:
I always make things functions as soon as I can give it a name. This has the added benefit of making your code more "self explaining".
The "const int" this mean you promise you won't change the values of b and h in your calculations.
The noexcept is another promise, but that's a whole topic on its own ;)
Related
In A Tour of C++ by Bjarne Stroustrup, some advice is listed at the end of each chapter. At the end of the first chapter one of them reads:
Avoid ‘‘magic constants;’’ use symbolic constants;
What are magic and symbolic constants?
somethingElse = something * 1440; // a magic constant
somethingElse = something * TWIPS_PER_INCH; // a symbolic one
The first is an example of the magic constant, it conveys no other information other than its value.
The latter is far more useful since the intent is clear.
Using symbolic constant also helps a great deal if you have multiple things with the same value:
static const int TWIPS_PER_INCH = 1440;
static const int SECTORS_PER_FLOPPY = 1440; // showing my age here :-)
That way, if one of them changes, you can easily identify which single 1440 in the code has to change. With magic 1440s scattered throughout the code, you have to change it in multiple places and figure out which are the twips and which are the sectors.
A magic constant would be a numeric value that you just type into some code with no explanation about why it is there. Coming up with a good example is challenging. But let's try this:
float areaOfCircle(float radius) {
return radius * radius * 3.14159
}
Here I've used a "magic constant" of 3.14159 without any explanation of where it comes from. It would be better style to say
const float pi = 3.14159
float areaOfCircle(float radius) {
return radius * radius * pi;
}
Here I've given the person reading the code some idea about where the constant came from and why it was used... it didn't seem to "magically" appear out of nowhere.
Magic:
int DeepThought() { return 42; }
Symbolic:
const int TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything = 42;
int DeepThought() { return TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything; }
I have code which has a lot of conversions from double to int . The code can be seen as
double n = 5.78;
int d = n; // double implicitly converted to a int
The implicit conversion from double to int is that of a truncation which means 5.78 will be saved as 5 . However it has been decided to change this behavior with custom rounding off .
One approach to such problem would be to have your own DOUBLE and INT data types and use conversion operators but alas my code is big and I am not allowed to do much changes . Another approach i thought of was to add 0.5 in each of the numbers but alas the code is big and i was changing too much .
What can be a simple approach to change double to int conversion behaviour which impact the whole code.
You can use uniform initialization syntax to forbid narrowing conversions:
double a;
int b{a}; // error
If you don't want that, you can use std::round function (or its sisters std::ceil/std::floor/std::trunc):
int b = std::round(a);
If you want minimal diff changes, here's what you can do. Please note, though, that this is a bad solution (if it can be named that), and much more likely leaving you crashing and burning due to undefined behavior than actually solving real problems.
Define your custom Int type that handles conversions the way you want it to:
class MyInt
{
//...
};
then evilly replace each occurence of int with MyInt with the help of preprocessor black magic:
#define int MyInt
Problems:
if you accidentally change definitions in the standard library - you're in the UB-land
if you change the return type of main - you're in the UB-land
if you change the definition of a function but not it's forward declarations - you're in the UB/linker error land. Or in the silently-calling-different-overload-land.
probably more.
Do something like this:
#include <iostream>
using namespace std;
int myConvert (double rhs)
{
int answer = (int)rhs; //do something fancier here to meet your needs
return answer;
}
int main()
{
double n = 5.78;
int d = myConvert(n);
cout << "d = " << d << endl;
return 0;
}
You can make myConvert as fancy as you want. Otherwise, you could define your own class for int (e.g. myInt class) and overload the = operator to do the right conversion.
I tried several time to find where is the problem, but I can not find any thing.So, could anyone help me to find the problem and why I can not see a result?
It might seem stupid question, but I new to programming world :)
This is my code :
#include <iostream>
using namespace std;
// There is the declraction of all functions
float max();
float min();
// This is the main program
int main ( int argc, char ** argv )
{
// Here you can find max
max(504.50,70.33);
// Here you can find min
min(55.77, 80.12);
return 0;
}
// This is the max function
int max(float a, float b){
float theMax;
if (a>b) {
theMax = a;
cout <<theMax ;
}
else{
theMax = b;
cout << b;
}
return theMax;
}
// This is the min function
int min( float c, float d){
float theMin;
if (c >d ) {
theMin =c;
cout << theMin;
}
else {
theMin =d;
cout << theMin;
}
return theMin;
}
You're calling std::max and std::min. That's because you wrote using namespace std, and did not declare your own min and max prior to using them. (You did declare two other min and max functions, but those take zero arguments, not two). So, when the compiler sees max(504.50,70.33); the only candidate is std::max.
You declare these overloads:
float max();
float min();
which are functions that take no arguments and return float.
You're calling
max(504.50,70.33);
and
min(55.77, 80.12);
which are functions that takes two doubles and may or may not return anything.
These match std::max and std::min, not the prototypes you declared.
You then define
int min( float c, float d){
which also doesn't match the prototypes you declared.
In other words, these functions are unknown in main, and the functions that are actually called are std::min and std::max.
Don't use using namespace std; - what you save in typing is lost in clarity and debugging.
You should also rename the functions - it's not a good idea to reuse standard library names.
I'm starting to learn C++. Here is a problem that I have:
#include <iostream>
using namespace std;
#define PI 3.14;
int main(){
double r = 5.0;
double circle;
double inp;
circle = 2 * PI * r;
cout << circle;
cin >> inp;
}
It shows error: error C2100: illegal indirection.
I've googled but found no answer. Thanks
#define PI 3.14;
The ; is wrong, delete it.
btw, your line expands to circle = 2 * 3.14; * r;
So the compiler is then complaining about the *r, which explains the error message.
Macros are (relatively) simple substitutions so, when you write:
#define PI 3.14;
circle = 2 * PI * r;
it actually ends up as:
circle = 2 * 3.14; * r;
effectively the two statements:
circle = 2 * 3.14;
* r;
That last line would be a perfectly valid expression (albeit it not a very useful one) if r were a pointer of some description. However, given it's a double, that's where you're getting the illegal indirection from.
The use of macros is something you should generally avoid nowadays except in very specific circumstances. The use of them to provide inline functions has been subsumed mostly by the inline keyword ("mostly", because the inline keyword is only a suggestion).
In addition, using it to provide constants can be better done (with the advantage of full type support and usually better debugging) with the const keyword.
In other words, your PI constant would be better written as something like:
const double PI = 3.141592653589;
Just about the only place I use the pre-processor nowadays is for conditional compilation.
As an aside, you probably meant circumference rather than circle. The former is the length around the outside of the circle, the latter isn't really a length value at all.
Here is my work on gradient descend algorithm
#include<iostream>
#include<math.h>
#include<float.h>
using namespace std;
double f_prime(double x)
{
return (double)(4.0*powf(x,3)-9.0*powf(x,2));
}
void gradient()
{
double x_old=0;
double x_new=6;
double eps=0.01;
double precision=0.00001;
while(abs(x_new-x_old)>precision)
{
x_old=x_new;
x_new=x_old-eps*f_prime(x_old);
}
cout<<" local minimum at : "<<x_new<<endl;
}
int main()
{
gradient();
return 0;
}
The above code gives me warnings of a non correct conversion from double to float, possible loss of data, so as a result it gives me some undefined values like -1.IND. Can anyone explain why this is?
abs is defined only for int and long types. For floating point numbers use fabs.
Change powf to pow although I'm not sure that will solve your problem.