首页 > 解决方案 > 浮点数 C++,如何在数组的每个元素末尾添加“f”

问题描述

我刚刚打开 filename.file ,将每个浮点数保存在向量“顶点”中,但它们保存为整数。需要将所有数字正确转换为浮点数。例如:从“1”到“1.00000f”或至少从“1”到“1.0f”。

/////filename.file
...
v 1.000000 1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 1.000000 1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 -1.000000
v -1.000000 -1.000000 -1.000000
v -1.000000 1.000000 1.000000
...
//////


std::vector<float> vertices;

std::ifstream file(filename); 

    std::string line;

    while (std::getline(file, line))
    {

        std::istringstream iss(line);

        std::string result;

        if (std::getline(iss, result, ' '))
        {

            if (result == "v")
            {



                while (std::getline(iss, token, ' '))
                {
                    std::istringstream iss1(token);

                    if (std::getline(iss1, word))
                    {
                        float word_float = std::stof(word);

                        //std::cout << word_float << std::endl;
                        vertices.push_back(word_float);
                    }
                }
            }
        }
    }

//Look what I got
for(std::size_t i = 0 ; i < vertices.size(); i++) {
 std::cout << vertices[i] << " ";
}

/* 每个元素 1 -1 1 ...

// 但是这些数字应该完全保存

1.000000f -1.000000f 1.000000f ... */

标签: c++arraysvectorfloating-pointfloating

解决方案


听起来您想要以下顺序的东西:

std::cout << std::fixed << std::setprecision(5) << value << "f";

例如:

float values[] = { 1.0f, -1.0f, 1.0f };

for (auto const &value : values)
    std::cout << std::fixed << std::setprecision(5) << value << "f\t";

结果:

1.00000f    -1.00000f   1.00000f

推荐阅读