-3

我的问题是这样的:假设我有 3 个变量(i = 1,j = 2,k =3)我想这样做:“a = 0.ijk”所以 a == 0.123 但这些变量在多个 for 下所以我将它们的值保存在数组上..

我尝试使用 sstream 将它们从字符串转换为 int (123) 然后我将其除以 1000 得到 0.123 但它不起作用...

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++;

有人可以帮助我吗?

4

2 回答 2

1

我对您的要求感到困惑,但这是您想要做的吗?

#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;
}
于 2018-03-09T22:59:09.277 回答
0

这是你想要达到的目标吗?

#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";
}
于 2018-03-09T23:11:31.833 回答