【问题标题】:Is there a way to use a for loop to divide your number有没有办法使用for循环来划分你的号码
【发布时间】:2022-11-30 04:41:32
【问题描述】:

我想用一个for/while循环来划分用户输入的数字。

比如我想让程序在输入的数可以被除的时候除以2。

假设用户输入了数字 8,那么答案是:

8 被 2 除 3(8/2=4;4/2=2;2/2=1)

下面的表达式是减法,我需要被除的数字。

#include <iostream>
using namespace std;

int main()
{
 int n;
 int counter = 0;

 cout << "Enter a positive integer n: "; 

 cin >> n;

 for(int k = n; k > 1; k--){
     
     cout<<"\nYour numbers are : " << k;
     counter++;
 }

 cout <<" \n your number is divded :" << counter << " times ";
  return 0;
}

【问题讨论】:

  • for 循环的最后一部分包含每次循环都会计算的表达式。目前,它是k--,而你想要k /= 2(或k = k / 2

标签: c++ loops for-loop math divide


【解决方案1】:

尝试这样的事情:

#include <iostream>
using namespace std;

int main()
{
 int n;
 int counter = 0;

 cout << "Enter a positive integer n: "; 

 cin >> n;

 for(int k = n; k >= 2; k /= 2){
   ++counter;
 } 

 /* alternatively:

 while (n >= 2){     
     n /= 2;
     ++counter;
 }
 */

 cout << "Your number is divided by 2 " << counter << " times";
  return 0;
}

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多