gpt4 book ai didi

c++ - 如何将多个值存储到一个数组中以便稍后打印出来?

转载 作者:行者123 更新时间:2023-11-30 04:08:26 26 4
gpt4 key购买 nike

好的,我将在这里插入我正在开发的这个程序的代码,以帮助我完成工作。我不想详细说明它是如何使用的,但最重要的是我正在创建一个程序:从用户那里获取两个值,对它们进行操作,然后将它们存储到一个数组中。

现在我可以用一个非常简单的线性程序来做到这一点,但我遇到困难的地方是当程序启动时它要求用户输入两个值,然后程序存储它,然后再次循环,它将要求用户再输入两个值,然后我希望它再次存储,存储的次数取决于用户需要的数据点数量,最后我希望它打印出他们输入的所有操作值,最后我想让它把它导出到一个 txt 文件,但那会在以后出现。我只想了解基本情况。谁能帮我解决这个问题?

#include <iostream>
#include <set>

double dCoordinates(double x)
{
return x / 1000;
}

void Store(int x , int y)
{
int anCoorValues[] = { x, y };
}

int main()
{
std::cout << "How many data points do you need to enter?" << std::endl;
int nAmountOfDataPoints;
std::cin >> nAmountOfDataPoints;

for (int nCount = 0; nCount < nAmountOfDataPoints; nCount++)
{
std::cout << "Enter E/W Coordinates" << std::endl;
double dEW;
std::cin >> dEW;

std::cout << "Enter N/S Coordinates" << std::endl;
double dNS;
std::cin >> dNS;

Store(dCoordinates(dEW),dCoordinates(dNS));
}
}

最佳答案

您应该在 main 中声明一个容器,然后在需要时将其作为参数传递给其他函数。然后在任何时候你都可以输出容器。在您的情况下,最好使用 std::vector<std::pair<double, double>>

例如(顺便问一下,为什么Store函数的参数是int类型的?)

#include <vector>
#includde <utility>

double dCoordinates( double x )
{
return x / 1000;
}

void Store( std::vector<std::pair<double, double>> &v, double x , double y )
{
v.push_back( { x, y } );
}

int main()
{
std::cout << "How many data points do you need to enter?" << std::endl;
int nAmountOfDataPoints;
std::cin >> nAmountOfDataPoints;

std::vector<std::pair<double, double>> v;
v.reserve( nAmountOfDataPoints ) ;

//...
// Here you can output the folled vector

for ( const std::pair<double, double> &p : v )
{
std::cout << "( " << p.first << ", " << p.second << " )" << std::endl;
}

关于c++ - 如何将多个值存储到一个数组中以便稍后打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21838315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com