Hi. I have a hopefully simple question on for loops and carrying variables over. I'm trying to write a function that shows more than the 16 decimal maximum precision when dividing.
My strategy: Use 1/x as the model. Iterate through x[1,20] (show the decimals from 20 numbers), and use a combination of modulus functions and subtraction to find each digit after the decimal place. Store the series of digits in a vector, which is then stored in a vector of vectors (because I don't know how long or how many numbers I'd like to work with).
Problem: My variables aren't carrying over properly. Perhaps an insightful C++ guru could provide a better approach or suggest a better way to declare components of my function.
More specifically, if I try multiple numbers, the digits don't carry out correctly. For example, I'll start with...
1/7 --> 10/7 (multiple numerator by 10 to make it big enough to divide into)
= 1 r 3 (1 times with a remained of 3).
Next round:
3/7 --> 30/7 (multiple numerator again)
= 4 r 2 (4 times with remainder of 2)
However, when I switch to another the next digit I want to find the decimal places for, such as 8 (e.g. 1/8), I run into issues.
It won't start at a multiple of 10 (e.g. 10, 100, 1000, etc), but uses the remainder from the previous iteration.
Any ideas?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
// the process of division
// d = denominator set
// b = vector of vectors (same size as d) (number 0 to size of d)
// c = vector of decimal values to be added to b as a row
void Divide(vector<int> d, vector< vector<int> > b, vector<int> c, int u) {
int v = 0;
int r, hold;
for (int i = 0; i < d.size(); i++) {
for (int x = 0; x < 1; x++) {
int count = 0;
hold = u = DivSet(d,u,i); // function described below
r = u%d.at(i); // r is the remainder from modulus
while (r < hold) {
hold -= d.at(i);
count++; // counts the number of times
} // needed to get to remainder value
v = count;
c.push_back(v); // stores this number in the vector
}
b.push_back(c); // adds new row of decimal values
cout << endl;
}
}
// checking if the number is divisible?
// currently working on making "u" big enough to divide
int DivSet (vector<int> d, int u, int i) {
bool check;
check = u < d.at(i);
if (check == true) {
u *= 10;
DivSet(d,u,i);
}
return u;
}
|