【问题标题】:How to pass and return arrays in C++? [duplicate]如何在 C++ 中传递和返回数组? [复制]
【发布时间】:2014-03-10 16:07:23
【问题描述】:

我正在制作一个简单的银行帐户处理系统,并将帐户信息保存为一个数组,但是在传递帐户信息时遇到了困难,我正在将数组从文本文件读取到程序中,但这需要从读取文件的函数传递到处理提款、存款和查看余额的函数,传递的数组旨在存储当前余额,作为透支的布尔值的替代品以及最近 3 次取款和存款。

withdraw 函数的样子

float Withdraw()                                        //function handled withdraw requests
{
//variables
const int M = 3;                                //declare const int for withdraws
const int N = 8;                                //declare const int for account
float withdrawAmount = 0.0f;                    //used for internam laths in function   
float currentBalance = 0.0f;                    //used internally in function
float newBalance = 0.0f;                        //passed to write function
float withdraws[M];                             //passed to write function
float account[N];                               //passed and returned from read function
//call readFile function
readFile(account[N]);

cout << account[0];
//user interface
cout << "Withdraw opnened" << endl;                 //prompts user for input of a withdraw amount and displays current balance
cout << "Your Current Balance is: " << currentBalance << endl;
cout << "How Much Would You Like to Withdraw?" << endl;
cin >> withdrawAmount;
newBalance = currentBalance - withdrawAmount;           //calculates balance after withdraw
withdraws[2] = withdraws[1];
withdraws[1] = withdraws[0];
withdraws[0] = withdrawAmount;
system("PAUSE");
system("cls");

writeFile(newBalance, withdraws[M]);
Menu();
return 0;
}

读取文件的函数看起来像

float readFile(float account[8])
{
//variables
const int N = 8;
float accountRead[N];

//read file
ifstream file("floats.txt");
if (!file.is_open())
{
    cerr << "Error opening file" << endl;
    return 0;
}
for (int i = 0; i < N && file >> accountRead[i]; ++i)
    ;
if (file)
{
}
account = accountRead;
return account[N];
}

任何指导都将不胜感激,因为我花了几个小时试图研究这个但无处可去

【问题讨论】:

  • '我已经花了好几个小时试图研究这个'这听起来很荒谬!只需查看相关部分下的右侧。
  • @πάνταῥεῖ 别管他 ;)

标签: c++ arrays parameters


【解决方案1】:

使用double,而不是float。例如。文字 3.14 的类型为 double。这是因为double 是 C++ 中的默认浮点类型,当没有真正重要的理由不这样做时,您理所当然地使用浮点类型。

使用std::vectorstd::array,而不是原始数组。

例如,您可以只从函数返回 std::vectorstd::array

另外,请记住

float readFile(float account[8])

等价于

float readFile(float account[])

float readFile(float* account)

但是std::vectorstd::array 不会有这个问题。

【讨论】:

  • 即使这样做我仍然收到一个错误,说我有“未解决的外部”经过一些研究这似乎是说我缺少某种包含有没有人知道这可能是吗?
  • 从技术上讲,这意味着链接器无法找到某些东西的编译定义,通常是函数。通常这是由于未编译和链接包含定义的源文件(例如,未包含在 IDE“项目”中)造成的。在一些罕见的情况下,但对于新手来说并不罕见,它是由声明和定义之间的不匹配引起的——这可以通过不要不必要地使用函数的前向声明来避免(这也是更少的工作)。
【解决方案2】:
readFile(account[N]);

这是错误的。您传递了最终值。

readFile(account);

这样更好。

return account[N];

而且您不能返回最终值。从数组中取消引用指针会导致未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2017-05-16
    相关资源
    最近更新 更多