在 c++ 中连接变量

Concatenating variables in c++

本文关键字:变量 连接 c++      更新时间:2023-10-16

我的问题是这样的:假设我有 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++;

有人可以帮助我吗?

我对

你在问什么感到困惑,但这是你想做的吗?

#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;
}

这是你想要实现的吗?

#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";
}