-3

my problem goes like this: Let's suppose i got 3 variables (i = 1, j = 2, k =3) I want to do this: "a = 0.ijk" so a == 0.123 But those variables are under multiple for's so i'm saving their value on array..

I tried using sstream to convert them from string to int (123) then i would divide it by 1000 to get 0.123 but it ain't working...

float arrayValores[ maxValores ];

ostringstream arrayOss[ maxValores ];

...

arrayOss[indice] << i << j << k;

                istringstream iss(arrayOss[indice].str());

                iss >> arrayValores[indice];

                arrayValores[indice] = ((arrayValores[indice])/1000)*(pow(10,z)) ;

                cout << arrayValores[indice] << "  ";

                indice++;

Can someone aid me?

  • 1
    What does `0.123` mean? Think about the *decimal* number system we work in (base 10). What does `12` mean? Is there another way you can write it? What about `0.123`? – Justin Mar 09 '18 at 22:44
  • You are aware that a floating point variable cannot exactly represent the value `0.1` or `0.02`? The best you can get will be an approximation. – Peter Mar 09 '18 at 23:03

2 Answers2

1

I'm confused as to what you're asking, but is this what you want to do?

#include <iostream>
#include <string>

using namespace std;

int main() 
{
    int i = 1;
    int j = 2;
    int k = 3;

// Create a string of 0.123
    string numAsString = "0." + to_string(i) + to_string(j) + to_string(k);
    cout << numAsString << '\n';

// Turn the string into a floating point number 0.123
    double numAsDouble = stod(numAsString);
    cout << numAsDouble << '\n';

// Multiply by 1000 to get 123.0
    numAsDouble *= 1000.0;
    cout << numAsDouble << '\n';

// Turn the floating point number into an int 123
    int numAsInt = numAsDouble;
    cout << numAsInt << '\n';

    return 0;
}
Zebrafish
  • 11,682
  • 3
  • 43
  • 119
0

Is this what you want to achieve?

#include <iostream>
#include <string>
#include <cmath>
#include <vector>

int main() {
    // your i, j, k variables
    std::vector<int> v = {1, 2, 3};
    double d = 0;
    for (int i = 0; i < v.size(); i++) {
        // sum of successive powers: 1x10^-1 + 2x10^-2 + ...
        d += pow(10, -(i + 1)) * v[i];
    }
    std::cout << d << "\n";
}
mirkomorati
  • 155
  • 1
  • 6