No matter if the condition is true if always executes in c++ - c++

Can someone correct this code please.
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int c;
double d;
double e;
double f;
double g;
f = a / b;
g = b / a;
c = 0;
cin >> a;
cin >> b;
f = a / b;
g = b / a;
if (a == b)
{
cout << a << endl;
return 0;
}
else if (f == int(f))
{
cout << a << endl;
return 0;
}
start:
while (a * b > c)
c = c + 1;
d = c / a;
e = c / b;
if (d == int(d))
if (e == int(e))
{
cout << c << endl;
return 0;
}
else if (d != int(d))
goto start;
else if (e != int(e))
goto start;
if (a * b <= c)
cout << a * b << endl;
}
No matter what the
else if(f==int(f))
code is always executed. Eg. I put in 3 and 5 and even though 3/5 gives a decimal the else if is always executed and outputs 3. WHAT AM I MISSING HERE?

The primary error in your code leading to the problem with the if statement is the integer division. You have to cast the operands to doubles to perform floating point division:
cin >> a;
cin >> b;
f = double(a) / double(b);
g = double(b) / double(a);
There are other issues to clean up, but this is the one that leads to your question.

These expression, though they are assigning to double variables, calculate integer divisions.
f = a / b;
g = b / a;
d = c / a;
e = c / b;
I.e. what gets assigned to the doubles are integer values.
Your if-conditions basically check for integer values and hence always evaluate to true.
In order to avoid the integer division and get actual floating point values assigned to the doubles, you need to make sure early that the compiler interprets them accordingly. E.g.:
f = (1.0*a) / b;
g = (1.0*b) / a;
d = (1.0*c) / a;
e = (1.0*c) / b;
And, as a comment points out, better always init all your variables (even if here a,b,c would be enough).
int a=1;
int b=1;
int c01;
double d=1.0;
double e=1.0;
double f=1.0;
double g=1.0;

You just need to define type a and b as double not int.

Related

My implementation of mathematical formula returns different value than calculator

using namespace std;
#include <iostream>
#define _USE_MATH_DEF
#include <conio.h>
#include <cmath>
int main()
{
const double e = 2.71;
double x, a, b, c, A, B, C, M;
cout << "Enter the value of x, a, b and c: ";
cin >> x >> a >> b >> c;
A = x + pow(sqrt(x + a), 3);
// cout << A;
B = x - sqrt((abs(x - b)));
// cout << B;
C = A / B;
M = pow(e, -1 * c) * C;
cout << "The result of function is " << M;
_getch();
return 0;
}
For example, lets define x=1, a=4, b=5, c=1.
Calculator returns M as -0.9547605358, but code calculates M as -4.49459.
This is mathematical formula that I need to code:
Here I see some problems, namely A must be
A = x + pow(sqrt(x + a), 1.0/3.0);
B and C definition is correct, but M must be
M = pow(e, -1 * c * x) * C;
I would also like to point out that conio.h is a non standard header file and _getch() is non standard.

why can't I assign the value of one variable to another? [duplicate]

This question already has answers here:
Scope of variables in if statements
(4 answers)
Closed 3 years ago.
I have two variables and I want to work with the bigger and the smaller one differently.
My approach:
a = 1;
b = 2;
if (a >= b){
int c = a;
int d = b;
}
else{
int c = b;
int d = a;
}
I obtained an error of unused variable and when I try to use c and d later, it says
c could not be resolved
Is there a way to solve this?
In both cases c and d are scoped to the braces in the if else block, so you can't access them outside that.
You need something of the form
int c, d;
if (a >= b){
c = a;
d = b;
} else {
c = b;
d = a;
}
As other have pointed out the issue here is where you declare the variables. You cannot use them outside of the scope they are declared in so you get an error.
If you can use C++17 then you can fix the code by using std::minmax and a structured binding like
int main()
{
int a = 5, b = 10;
auto [min, max] = std::minmax(b, a);
std::cout << min << " " << max;
}
which is really nice because now you don't have variables that are uninitialized for any amount of time.
It's because you are declaring the variables in an if statement.
Logically you may be of the belief that the else in a way guarantees that the variables will be assigned if the declaration is in both the if and also in the else block.
The correct way to do it is to just declare the variables before the if block, otherwise the variables use will be restricted to the scope from which it was declared.
Also, you can do this without the need for an if and else by using ternary operations:
int a = 1;
int b = 2;
int c = a >= b ? a : b;
int d = b < a ? b : a;
With this type of syntax, you can save yourself the hassle of writing if and else blocks for simple variable assignments. The variable after the ? is the result if the condition is true, and the variable after the : is the result if the condition is false.
That's a scope problem, you are creating the variables inside a scope and they can't be accessed outside
if (a >= b){
int c = a; // c and d belongs to that if scope
int d = b;
}
else{
int c = b; // c and d belongs to that else scope
int d = a;
}
Change your code to this :
a = 1;
b = 2;
int c;
int d;
if (a >= b){
c = a;
d = b;
}
else{
c = b;
d = a;
}
// You can now call c and d there
A way to shorten that code would be to store the boolean value of a >= b and use it in a ternary expression to set c and d
In example :
a = 1;
b = 2;
bool IsAGreaterOrEqualToB = (a >= b);
int c = ((IsAGreaterOrEqualToB) ? (a) : (b));
int d = ((IsAGreaterOrEqualToB) ? (b) : (a));

Trying to calculate GCD in C++

I think I am not calling the function or passing it correctly. Here are a couple of snippets that I am having issues with.
Using test data, 1/2 and 8/16 returns 1/2 instead of 1/1.
This is my code to calculate the GCD:
void Fractions::gcd(int n, int d)
{
int a,b,c;
a = n;
b = d;
while (a%b != 0)
{
c = a % b;
a = b;
b = c;
}
num = n/b;
denom = d/b;
}
This is the code that calculates will add numbers from input and calculate the GCD based from those numbers:
Fractions Fractions::operator+(Fractions& fraction2)
{
Fractions totalAddition;
totalAddition.num = (num * fraction2.denom + denom * fraction2.num);
totalAddition.denom = (denom * fraction2.denom);
totalAddition.gcd(num, denom); // i think issue is here
return totalAddition;
}
The only problem here is the name of the function.
A function called gcd should return the Greatest Common Divisor:
int gcd(int n, int d) {
int a, b, c;
a = n;
b = d;
while (a % b != 0) {
c = a % b;
a = b;
b = c;
}
return b;
}
It doesn't need to be a member function of Fraction to do this - it can be a standalone function, which is better, as it makes Fraction more encapsulated. But you can give it an overload which digests Fraction:
int gcd(const Fraction& frac){
return gcd(frac.numerator(), frac.denominator());
}
The name gcd is on the terse side but clear enough in context.
What your function is doing is it's simplifying a fraction, as a member function of a Fraction object, and overwriting that Fraction's member variables. So, it should be called simplify, and it doesn't need to take any input:
void Fractions::simplify() {
int a, b, c;
a = num;
b = denom;
while (a % b != 0) {
c = a % b;
a = b;
b = c;
}
num = n / b;
denom = d / b;
}
You might find you don't need a gcd function in which case simplify will be enough. But if you do need both functions, you can avoid some duplication of code here:
void Fractions::simplify() {
int g = gcd(*this);
num /= g;
denom /= g;
}
//Euclidean algorithm
//if b<a the gcd(a,b)=gcd(a-b,b)
int gcd(int a,int b)
{
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}
Output
15 12
3
//Optimal implementation of Euclidean Algorithm
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
Output
15 12
3

How to convert integer to double implicitly?

int a{5},b{2},c{9};
double d = (double)a / (double)b + (double)c;
Or I can use static_cast. Either way is verbose, especially when the formula is long. Is there a better solution?
You can multiply by 1.0:
int a{5}, b{2}, c{9};
double d = 1.0 * a / b + 1.0 * c;
And when you work with sums you can add to 0.0:
double d = 0.0 + a - b + c;
Most compilers perform optimization such that the meaningless operation is not evaluated. Only type conversion is done.
Remember that you only need to cast the first member in each division/multiply group. Do so in any manner that seems reasonable. And simple addition/substraction (with no other type multipliers/divisors) is casted too. Compilers guarantee casting. So your example:
double d = (double)a / (double)b + (double)c;
Really may be rewritten like this:
double d = (double)a / b + c;
double d = 1.0 * a / b + c;
double d = static_cast<double>(a) / b + c;
Some more examples:
double d = (double)a / b + (double)c / d + e;
double d = 1.0 * a / b + 1.0 * c / d + e;
double d = static_cast<double>(a) / b + static_cast<double>(c) / d + e;
This works but all you need is a single 1.0* in front of a
int a{5},b{2},c{9};
double d = (double)a / (double)b + (double)c;
int a{5},b{2},c{9};
double d = 1.0*a / b + c;
The rules of precedence and implicit conversion will cause all the variables to be converted to doubles.
One thing to be careful of is grouped variables which will need to have their own 1.0* or 0.0+ as appropriate:
int a{5},b{2},c{9};
double d = a / (0.0 + b + c);
int a{5},b{2},c{9};
double d = a / (1.0 * b * c);
Alternately, one use use a static cast on the associated variable. I prefer the smaller version as the 1.0* or 0.0+ both scream out implicit conversion to doubles.
int a{5},b{2},c{9};
double d = a / (static_cast<double>(b) * c);
Is there a better solution?
Yes. Express intent through functions.
Marvel as the optimiser emits perfectly efficient assembler. Enjoy the accolades of your colleagues who gaze in wonder at your awesomely readable and maintainable code:
#include <iostream>
auto a_over_b_plus_c(double a, double b, double c)
{
double d = a / b + c;
return d;
}
int main()
{
int a = 5, b = 2, c = 9;
std::cout << a_over_b_plus_c(a, b, c) << std::endl;
}
For fun, here's a solution based on tuples & lambdas:
#include <iostream>
#include <tuple>
template<class T, class...Args>
auto to(Args&&...args)
{
return std::make_tuple(T(std::forward<Args>(args))...);
}
int main()
{
int a = 5, b = 2, c = 9;
auto calc = [](auto&& vals) {
auto& a = std::get<0>(vals);
auto& b = std::get<1>(vals);
auto& c = std::get<2>(vals);
return a / b + c;
};
auto result = calc(to<double>(a, b, c));
std::cout << result << std::endl;
}
... and something perhaps more readable...
#include <iostream>
#include <tuple>
#include <complex>
template<class T, class F, class...Args>
auto with(F f, Args&&...args)
{
return f(T(std::forward<Args>(args))...);
}
int main()
{
int a = 5, b = 2, c = 9;
auto calc = [](auto&& a, auto&& b, auto&& c) {
return a / b + c;
};
auto result = with<double>(calc, a, b, c);
auto result2 = with<float>(calc, a, b, c);
auto result3 = with<std::complex<double>>(calc, a, b, c);
auto result4 = with<std::complex<float>>(calc, a, b, c);
std::cout << result << std::endl;
std::cout << result2 << std::endl;
std::cout << result3 << std::endl;
}

How can i format a decimal to a fraction with limits to the denominator

Hi All I am trying to format a decimal A into a fraction B + C/D, where certain limit is imposed on D, say D could be one among [2...9] or [2...19] etc. BCD are integers
The goal is to get the formatted fraction as close to the decimal as possible.
Is there an existing algorithm/theory on this?
Or is there any API I can call on Mac SDK?
// Not tested or even compiled :-). Assumes you are handling sign
// in: a - the decimal to convert
// limit - the largest denominator you will allow
// out: outN - Numerator
// outD Denominator
#include <math.h>
void d2f(double a, int limit, int& outN, int& outD) {
double z;
int dPrev, d, n;
a = fabs(a);
z = a;
d = 1;
n = a;
dPrev = 0;
while (a - (double)(n/d) != 0 && z != floor(z)) {
z = 1 / (z - floor(z));
int tmp = d;
d = d * (int)floor(z) + dPrev;
if (d > limit) {
d = tmp;
break;
}
dPrev = tmp;
n = floor(a * d + 0.5);
}
outN = n;
outD = d;
}
Hope that helps/works :-)
Look into continued fractions.