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

如何在main函数中打印自定义函数的返回值?

解决幂计算函数的返回值打印及逻辑问题

一、打印函数返回值的两种方式

你可以直接在cout中调用函数输出返回值,也可以先把返回值存入变量再打印,两种方式都可行:

方式1:直接输出函数返回值

#include <iostream>
using namespace std;

int powerCalculation(int base, int exponent);

int main()
{
    int options = 3; // 示例值,实际根据你的逻辑赋值
    int base = 2;    // 示例底数
    int exponent = 3;// 示例指数
    if (options == 3)
    {
        // 直接调用函数并打印返回值
        cout << powerCalculation(base, exponent) << endl;
    }
    return 0;
}

方式2:先存变量再打印

如果需要后续复用计算结果,推荐用这种方式:

#include <iostream>
using namespace std;

int powerCalculation(int base, int exponent);

int main()
{
    int options = 3;
    int base = 2;
    int exponent = 3;
    if (options == 3)
    {
        // 把函数返回值存入变量
        int result = powerCalculation(base, exponent);
        // 打印变量
        cout << result << endl;
    }
    return 0;
}

二、修正powerCalculation的逻辑错误

你当前的幂计算函数存在逻辑问题:

  • 初始值result = base加上循环条件i <= exponent,会导致多乘一次底数。比如底数2、指数3,最终会算出2*2*2*2=16,而正确结果应该是8。
  • 没有处理指数为0的情况(任何非0数的0次方都是1)。

修正后的函数如下:

int powerCalculation(int base, int exponent)
{
    // 处理指数为0的特殊情况
    if (exponent == 0)
    {
        return 1;
    }
    int result = 1;
    int i = 0;
    // 循环exponent次,每次乘底数
    while (i < exponent)
    {
        result *= base;
        i++;
    }
    return result;
}

完整可运行代码

#include <iostream>
using namespace std;

int powerCalculation(int base, int exponent);

int main()
{
    int options = 3;
    int base = 2;
    int exponent = 3;
    if (options == 3)
    {
        int result = powerCalculation(base, exponent);
        cout << result << endl;
    }
    return 0;
}

int powerCalculation(int base, int exponent)
{
    if (exponent == 0)
    {
        return 1;
    }
    int result = 1;
    int i = 0;
    while (i < exponent)
    {
        result *= base;
        i++;
    }
    return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:02:25