鱼C论坛

 找回密码
 立即注册
查看: 938|回复: 1

[已解决]C++问题

[复制链接]
发表于 2020-11-18 01:56:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
a)        What is the exact output of the code below if we execute the function call q2(20)?  如果执行函数调用q2(20),下面代码的确切输出是什么?
  
void q2(int n)
{
    for (int i = 1; i < n; i *= 2)
        cout << i;
}

b)        The function in part (a) uses a for loop. Rewrite the function using a while loop  without changing how the code works。(a)部分中的函数使用for循环。 使用while循环重写函数,而无需更改代码的工作方式。

c)        Rewrite the function from part (a) using a do-while loop. (Hint: make sure the code produces the same output for all cases). 使用do-while循环重写部分(a)中的函数。 (提示:请确保代码在所有情况下都产生相同的输出)。



最佳答案
2020-11-18 08:47:40
本帖最后由 xieglt 于 2020-11-18 09:11 编辑

a)q2(20)输出:124816

b)

  1. void q2(int n)
  2. {
  3.      int i = 1;
  4.      while(i<n)
  5.      {
  6.            cout << i;
  7.            i*=2;
  8.      }
  9. }
复制代码

   
c)

  1. void  q2(int n)
  2. {
  3.         int i = 1;
  4.         do
  5.         {
  6.              cout << i;
  7.              i*=2;
  8.         }while(i<n);
  9. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-11-18 08:47:40 | 显示全部楼层    本楼为最佳答案   
本帖最后由 xieglt 于 2020-11-18 09:11 编辑

a)q2(20)输出:124816

b)

  1. void q2(int n)
  2. {
  3.      int i = 1;
  4.      while(i<n)
  5.      {
  6.            cout << i;
  7.            i*=2;
  8.      }
  9. }
复制代码

   
c)

  1. void  q2(int n)
  2. {
  3.         int i = 1;
  4.         do
  5.         {
  6.              cout << i;
  7.              i*=2;
  8.         }while(i<n);
  9. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-3 03:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表