There are 3 numbers (in fact, there may be more than one hundred, this is for example), for example

10, 80, 10

In sum, they should be equal to 100, can be fractional. If the first is increased by 10, then it will be 20

20, x, y

x and y in the sum must mean to be equal to 80, and the ratio of the finite numbers x and y should be preserved.

  • if we add something somewhere, then something must be taken away from somewhere?) I didn’t quite understand how it should work, but if you are to (10) + 10, then you need to take 10 from the rest, or randomly count the number , which you want to take away, but that they would not exceed 10 in total - Gorets
  • the ratio of x and y numbers should be preserved - jkeks

1 answer 1

So it will not go (using the gmp library)?

#include <gmp.h> #include <gmpxx.h> using namespace std; int main() { string str; vector<mpq_class> v; stringstream ss (stringstream::in | stringstream::out); mpq_class add, sum = 0, ratio; vector<mpq_class>::iterator i; getline(cin, str); ss.str(str); while(!ss.eof()) { mpq_class w; ss >> w; v.push_back(w); } v.pop_back(); // почему-то вводится лишнее число cin >> add; for(i = v.begin() + 1; i != v.end(); i++) sum += *i; ratio = (sum - add)/sum; cout << v[0] + add; for(i = v.begin() + 1; i != v.end(); i++) cout << ' ' << *i * ratio; cout << endl; return 0; } 

Translation g++ jkeks.c++ -lgmpxx -lgmp If you do not use gmp, then rational numbers can be realized in pairs of integers (you just need to write operator >>, operator << and the reduction of fractions). Using float / double is fraught with rounding errors in the case of recurring fractions (the denominator is not a power of two). For example 10 80 10 answer 20 640/9 80/9

  • wah .. how clever, I have already found the solution, it turned out to be single-line and beautiful, first we calculate the coefficient on the difference of the amounts that were written, and then multiply the remaining ones by it. True, one person helped me too. - jkeks
  • one
    And to bring a beautiful decision is not destiny? - alexlz
  • @jkeks, ratio is that coefficient. The code is simply not obvious enough, at least in my opinion :) For example, at first glance, it is not clear that sum is the sum of all elements except the first. And the user may want to add not to the first element, but to some other one) - insolor