【问题标题】:Concatenating variables in c++在 C++ 中连接变量
【发布时间】:2018-03-09 22:40:02
【问题描述】:

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

有人可以帮助我吗?

【问题讨论】:

  • 0.123 是什么意思?想想我们使用的 十进制 数字系统(以 10 为底)。 12 是什么意思?有没有别的写法? 0.123呢?
  • 您知道浮点变量不能准确表示值0.10.02?你能得到的最好的将是一个近似值。

标签: c++ concatenation sstream


【解决方案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;
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多