+ 1
I need help on c++
The question is how can I specifically print out a fraction a good example is 1/2 - 3/4 = -1/4 but I want the fraction not the value plus make sure to define it as a/b - c/d a = 1 b= 2 etc...
15 Antworten
+ 3
Try this, should help:
#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int numerator_a = a * d;
int numerator_b = c * b;
int denominator = b * d;
cout << a << "/" << b
<< " - "
<< c << "/" << d
<< " = "
<< (numerator_a - numerator_b)
<< "/"
<< denominator
<< endl;
}
You get -2/8 which is -1/4.
+ 2
you should use gcd to reduct the resulted fraction, as by just multplying each term, you should quickly come to overflow problems ;P
+ 2
boba
//for that you need to find a way, like
#include <iostream>
using namespace std;
int main() {
int a = 1, b = 2, c = 3, d = 4;
// if need use double
cout<< (a*d - b*c)<<"/"<<(b*d);
//further more to get reduced result find gcd of those numbers....
}
0
What the difficulty there you getting? Where is your code ? Post it..
boba
Take variables as double or float...
0
Did you not understand my question im a beginner... Jayakrishna🇮🇳
0
boba
Beginner or not, you have to try it first by yourself and then ask with your try if it unsolved...
You can just take variables doubles or float type and assign values..
Then just do :
cout<< (a/b - c/d) ;
0
Jayakrishna🇮🇳 here
0
Sir I want the fraction not the value?
0
-1/4
0
boba
Please add C++ in your thread tags, and it'd be nice if you don't put a question in the tags like "how can I print out a fraction". "C++ fraction" will be fine 👌
0
I want the value to be -1/4
0
Bless you Luk
0
Once you get more advanced in Object oriendted programming, this would be a nice example to use a class (or struct).
Define a class Fraction with the members numerator and denominator, which are initialised via the consteuctor. Overload the operators +,-, * and /.
Create a public function reduce, which you make use of in the overloaded operations.
- 1
//1/2=0
//int/int result int type only so take atleast one as double or float to get fraction part also..
#include <iostream>
using namespace std;
int main() {
double a = 1, b = 2, c = 3, d = 4;
double fraction = (a/b - c/d);
cout << fraction << endl;
}
edit:
boba
//for that you need to find a way, like
#include <iostream>
using namespace std;
int main() {
int a = 1, b = 2, c = 3, d = 4;
cout<< (a*d - b*c)<<"/"<<(b*d);
}