首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我在哪里可以在Stroustrup的书Programming Principles & Practices上找到“尝试这个”的解决方案?

我在哪里可以在Stroustrup的书Programming Principles & Practices上找到“尝试这个”的解决方案?
EN

Stack Overflow用户
提问于 2020-12-21 04:22:26
回答 1查看 48关注 0票数 1

我只需要仔细检查一下我的解决方案,但我在网上找不到任何解决方案。

如果你能帮助我,我会很高兴的,因为我已经为自己设定了在假期学习c++的目标。

特别是,我需要一个功能练习的帮助,这是我到目前为止所得到的:

代码语言:javascript
复制
//(not using multiplication)
int square(int a)
{
    int result = 0;
    int count = 0;
    while (count < a)
    {
        result += result;
        ++count;
        return result;
    }
}

int main()
{
        int x = 0;
        x = square(5);
        cout << x;
}

但我的输出是0。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-21 04:28:15

result0,所以将它添加到自身中,无论多少次,都会产生0。如果您正在尝试平方a,则应将其添加到result中。此外,return语句应该在循环之外,而不是在循环内部:

代码语言:javascript
复制
int square(int a)
{
    int result = 0;
    int count = 0;
    while (count < a)
    {
        result += a; // Here!
        ++count;
    }
    return result;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65384436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档