我如何打印浮动矢量?

时间:2018-03-28 23:53:04

标签: c++ vector

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

Character.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);
};

Character.cpp

#include "stdafx.h"
#include "Character.h"
#include <ctime>
#include <iostream>

void Character::printCharacter() 
{
  cout << "Enter First Name" << endl;
  cin >> firstName;
  cout << "Enter Last Name" << endl;
  cin >> lastName;
  cout << endl;
  cout << firstName << " " << lastName << ": " << endl;
  cout << "Health: " << healthPoints << endl;
  cout << "Position: "<<endl;

  for (auto i=0; i<position.size(); i++) 
  { 
    srand(time(NULL));
    position.push_back(f);
    cout << position[i] << endl;
  }
}

的main.cpp

#include "stdafx.h"
#include "Character.h"

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

  ch->printCharacter();
  system("pause");
  return 0;
}

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

position.reserve(3);
for (int i=0; i<position.size(); i++) 

reserve()不会更改vector的大小。所以你的vector保持为空,循环永远不会运行。

此外,您应该只调用srand()一次,并在循环中生成随机值,除非您希望它们全部相同。

float f = rand() / (RAND_MAX + 1) + 12 + (rand() % 4);

rand()返回的int小于RAND_MAX,因此该分组会产生0。  因此,您可以用以下代码替换该表达式:

float f = 12 + rand() % 4;

由于右侧是int,因此f将为12.013.014.015.0

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

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