【问题标题】:How can I get the highest value generated from within a function using struct C++如何使用 struct C++ 从函数中获取最高值
【发布时间】:2018-07-18 06:02:55
【问题描述】:

所以我试图显示产生兴趣最高的帐户,但由于某种原因它不起作用?任何帮助深表感谢。我遇到的错误与底部的 if 语句有关。

#include "stdafx.h"

#include <iostream>

using namespace std;

const int MAXACCOUNTS = 8;

struct Account
{
    int AccountNumber;
    double Balance;
    int DaysSinceDebited;
    double Interest;
};

int main()

{
    double highestInterest = 0;
    int highestInterestAccountIndex;

    Account accounts[MAXACCOUNTS] = { {1001,4254,40,20},{7940,27006.25,35},{4382,123.50,2},{2651,85326.92,14},{3020,657.0,5},{7168,7423.34,360},{6245,4.99,1},{9342,107864.44,45} };

    for (int index = 0; index < MAXACCOUNTS; index++)
    {
        if (accounts[index].Balance > 10000 || accounts[index].DaysSinceDebited > 30)
        {
            accounts[index].Interest = accounts[index].Balance * 0.06;
        }
        else
        {
            accounts[index].Interest = accounts[index].Balance * 0.03;
        }

        cout << "Account number: " << accounts[index].AccountNumber << " Balance: " << accounts[index].Balance << " Interest Paid: " << accounts[index].Interest << endl;

    }

    for (unsigned int index = 0; index < MAXACCOUNTS; index++)
    {
        accounts[index] = { AccountNumber[index], Balance[index], DaysSinceDebited[index] };

        double increment = CalcInterest(accounts[index]);

        if (increment >= highestInterest)
        {
            highestInterest = increment;
            highestInterestAccountIndex = index;
        }
    }

    std::cout << "The account that generated the greatest interest was account " << accounts[highestInterestAccountIndex].accountNumber << " With a total interest of " << highestInterest;


    system("pause");

    return 0;
}

我也必须以这种格式使用结构,但我不知道哪里出错了。

【问题讨论】:

  • 有什么错误?您是否使用调试器单步执行了您的程序?
  • 为什么要在第二个循环中重新分配accounts[index]AccountNumberBalanceDaysSinceDebited 数组从何而来?
  • 没有CalcInterest()的声明。
  • 来自结构 Accounts。我对此真的很陌生并且有点挣扎。
  • 您不能将结构成员用作普通变量。 AccountNumber[index]accounts[index].AccountNumber 不同。

标签: c++ arrays function struct


【解决方案1】:

去掉这些行:

    accounts[index] = { AccountNumber[index], Balance[index], DaysSinceDebited[index] };
    double increment = CalcInterest(accounts[index]);

你在main()开头初始化的时候已经填好了accounts[index]。没有名为AccountNumberBalanceDaysSinceDebited 的数组,它们只是Account 结构的成员。

并且没有函数CalcInterest(),兴趣已经在结构中。因此,您可以将第二行更改为:

double increment = accounts[index].Interest;

您还有一个错字:最后一行cout 中的accounts[highestInterestAccountIndex].accountNumber 应该是accounts[highestInterestAccountIndex].AccountNumber

【讨论】:

  • 您在最后一行 cout 中有错字,您写的是 accountNumber 而不是 AccountNumber。您没有收到指出这一点的错误消息吗?
  • 一旦我修复它编译时没有错误并且工作正常。
猜你喜欢
  • 1970-01-01
  • 2014-11-01
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
相关资源
最近更新 更多