C++ 如何打印浮点向量?

C++ 如何打印浮点向量?,c++,vector,C++,Vector,我试图让一个向量包含三个浮点数,一个代表x,一个代表y,一个代表z。现在,我在向量中添加了随机整数,现在我试图打印它,这样我就可以看到位置值,但我似乎无法正确打印。有人能检查一下这个代码,看看我遗漏了什么吗?多谢各位 字符.h #include <ctime> #include <string> #include <vector> #include <iostream> using namespace std; class Character

我试图让一个向量包含三个浮点数,一个代表x,一个代表y,一个代表z。现在,我在向量中添加了随机整数,现在我试图打印它,这样我就可以看到位置值,但我似乎无法正确打印。有人能检查一下这个代码,看看我遗漏了什么吗?多谢各位

字符.h

#include <ctime>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

class Character
{
  public:
    Character();

    void printCharacter();

    string firstName;
    string lastName;
    int healthPoints=rand() % 100;
    vector<float> position;
    float f = rand() / (RAND_MAX + 1) + 12 + (rand() % 4);
};
rand()。
因此,可以将该表达式替换为:

float f = 12 + rand() % 4;
由于右侧是一个
int
,因此f将是
12.0
13.0
14.0
15.0


您可以像这样实现构造函数:

Character::Character()
: position(3)
{
}

可以使用基于范围的for循环:

for (auto posit : position)
{
    cout << posit << endl;
}
for(自动定位:位置)
{

CooT发布一些可编译代码,并确切地说“我不能打印正确”的意思。我添加了其余代码。浮点在.exe窗口中不会输出。<代码>类特征()/{Cord>:在任何C++书籍或教程中,您会看到一个用括号定义的类<代码>()。
像这样吗?我没有复制和粘贴代码,我只是键入了我需要的内容。这只是这里的一个输入错误。@Damonlaws我没有复制和粘贴代码,我只是键入了我需要的内容--不要键入代码。实际上,在编辑窗口中复制和粘贴准确的代码。如果你遇到编译器错误,粘贴了伪代码,那么t浪费每个人的时间。那么我会像这样设置声明吗?向量位置(3);但是有了它,我得到了错误“需要一个类型标识符”@Damonlaws,你确定吗?你在使用什么编译器?我在使用MSVC for visualstudio2017@Damonslaws,像
向量位置(3)这样的声明没有错
。你肯定还有其他问题。@Damonlaws更好的方法是,选择一个bug,构建一个示例程序,其中包含该bug、整个bug,并且只包含该bug。如果将该bug隔离到最基本的部分并不能告诉你如何修复它,那么就提出一个问题
float f = rand() / (RAND_MAX + 1) + 12 + (rand() % 4);
float f = 12 + rand() % 4;
Character::Character()
: position(3)
{
}
for (auto posit : position)
{
    cout << posit << endl;
}
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Character
{
private:
    vector<float> position;
    float f;

public:
    Character()
    {
        populateCharacter(5);
    }

    //I separated out the push and print as separate functions
    void populateCharacter(int vectorSize)
    {
        for(int i = 0; i < vectorSize; i++){
            f = rand() / (RAND_MAX + 1) + 12 + (rand() % 4);
            position.push_back(f);
        }
    }

    void printCharacter()
    {
        cout << "Position: "<<endl;

        for (auto posit : position)
        {
            cout << posit << endl;
        }
    }
};

int main()
{
    Character* ch = new Character;

    ch->printCharacter();
    delete ch;
    return 0;
}