+ 4
Change a string of a fraction into integer and do math with it and returns as a fraction.
https://code.sololearn.com/cmy8Ux5D458v/?ref=app I have been looking for a way for sometime and I can’t find any? Anyone have an idea.
13 Réponses
+ 1
That helps alot i appreciate the hep Jayakrishna🇮🇳
0
Example?
0
Jayakrishna🇮🇳 What do you mean bu example?
0
Sry question is not understood by me..
Can you add any sample input and expected output?
0
Jayakrishna🇮🇳 str1 = "3/4" int = 5; are the input and the "3/20" is the output
0
what's your idea here?
How 3/20 came? 3/(4*5)?
0
Yes
0
#include<iostream>
using namespace std;
int main() {
std::string str1 = "3/4";
int amout_serving = 5;
// get substring after / by find() method and substr method as
int x = str1.find('/'); // gets '/' position
//next get after / substring ie 4 , and convert it into int by stoi() then multiply by amount_serving
int y = amout_serving * stoi(str1.substr(x+1)); // 5*4 => 20
// add this y to "3/" substring
string result = str1.substr(0,x+1) + to_string(y);
cout<< result;
}
//Yones Mussa hope it helps....
0
Jayakrishna🇮🇳 i appracite your answer but what if i have something like “7-1/3” as a string and 2 as integer which the output that i am looking for is 3/11. Im look for a way that basically solve both statements at the same time. Not hardcode it.
0
Yones Mussa
Can you tell me how 7-1/3 *2 = 3/11.?
You did not tell it in general. I thought only one case..
According to 3/4 * 5 = 3/20
But in general maths (3/4) *5= 15/4
And
7 - 1/3 = (21-1) /3 =(20/3) *2=> 40/3
If you want to operate arithmatics why don't take input as double type input numbers?
By using string, you need hardcode it as required format..
You can try your own way, with the methods I mentioned in program.
Give it a try!!...
Hope it helps..
0
Jayakrishna🇮🇳 it does help. I manged to get a program that take a double like 2.5 to 1 -1/4 but now it seems impossible to convert the the string of “2-1/2 “ to 2.5 or “3/4” to .75
0
Yones Mussa
for single operation , you can do this way but for compound statement of multiple operands , you to find an algarithm which works like a compiler, which performs all operations...
https://code.sololearn.com/czsMSQ9rJl3G/?ref=app
if it allowed you to take input of double, then that's easier to do task, instead of making it complex evaluation of string..
edit:
hope this is you may looking..
https://www.geeksforgeeks.org/expression-evaluation/amp/
hope it helps...
- 1
.