You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++查找用户最高余额时出现编译错误求助

解决C++查找最高账户余额的代码错误

核心错误点及修复方案

  • 循环条件错误:userAccount是你定义的结构体类型,不能用来作为循环的数值判断条件。你之前用count变量记录了实际输入的用户数量,循环上限应该用count,而非结构体类型名。
  • 余额变量访问错误:循环里直接使用的account_balance是输入阶段的局部变量,并非当前遍历到的用户账户余额。需要通过数组accts访问每个用户的余额,即accts[i].account_balance。
  • 类型不匹配问题(次要):结构体中account_balance定义为int类型,但输入时用float变量存储,赋值会丢失小数部分。如果需要支持小数余额,建议将结构体里的account_balance改为float或double。

修正后的完整代码

#include <iostream>
#include <string>
using namespace std;

struct userAccount {
    std::string username;
    int age;
    std::string nationality;
    // 改为float支持小数余额,无需小数可改回int
    float account_balance;
};

int main() {
    userAccount accts[20];

    cout << "Enter name, age, nationality, and balance separating with space:" << endl;

    string username;
    int age;
    int count = 0;
    string nationality;
    float account_balance;
    while (cin >> username >> age >> nationality >> account_balance) {
        userAccount user;
        user.username = username;
        user.age = age;
        user.nationality = nationality;
        user.account_balance = account_balance;
        accts[count] = user;
        count++;    
    }

    float highestBalance = 0.0; 
    // 用count遍历实际输入的所有用户
    for (int i = 0; i < count; i++) {
        // 访问数组中第i个用户的余额
        if (accts[i].account_balance > highestBalance)
            highestBalance = accts[i].account_balance;    
    } 

    cout << "The highest balance out of everyone is: $" << highestBalance << endl;
    return 0;
}

额外说明

  • 若要限制最多20个用户,循环条件也可写为i < 20,但用count更精准,能适配实际输入用户数量少于20的情况。
  • 若无需处理小数余额,将结构体和输入变量的float改回int即可,不影响核心逻辑。

内容的提问来源于stack exchange,提问作者Jbazzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 22:11:14