连续操作与C++
successives operations with C++
如何执行此代码:
if a number n is divisible by 3, add 4 to n;
if n is not divisible by 3 but by 4, divise n by 2;
if n is not divisible by 3, not by 4, make n=n-1.
我的问题是我不知道如何连续制作这个。例如:对于数字 6,我必须有:
6, 10, 9, 13, 12, 16, 8, 4, 2, 1 et 0
6+4=10; 10-1=9; 9+4=13; 13-1=12; 12+4=16; 16/2=8.....0
这会产生 10 个操作。
所以我的程序必须返回:6---10
谢谢你的帮助
使用取模运算符 (%),可以计算除法的余数。这通常是程序决定n是否可以被f整除的方式。
iterations = 0;
while (n != 0) {
if (n % 3 == 0) n+=4;
else if (n % 4 == 0) n /=2;
else n--;
iterations++
}
你必须使用 @jubjub 的代码进行循环,直到序列达到 0,计算循环的次数:
#include <iostream>
#include <cmath> // pour exp()
using namespace std;
int main()
{
for (int n=0; n<9; ++n)
{
int count = 0, next = n;
while (next != 0 && count >= 0)
{
if (next % 3 == 0)
next += 4;
else if (next % 4 == 0)
next /= 2;
else
next --;
count ++;
}
if (count < 0)
cout << "n=" << n << ": could not converge to 0" << endl;
else
cout << "n=" << n << ": required " << count << endl;
}
return 0;
}
我不知道对于这个特定的系列,是否有证据表明它总是在少于依赖于 n 的步数内收敛到零。但是我已经包括了一个警卫,以防"计数"环绕到负数。
我建议采用递归方法:
int num_ops(int num, int prev_ops) {
if(num == 0) return prev_ops;
if((num % 3) == 0)
return num_ops(num+4, prev_ops+1);
if((num % 4) == 0)
return num_ops(num/2, prev_ops+1);
else
return num_ops(num-1, prev_ops+1);
}
首次调用 num_ops 时,请确保 prev_ops 参数为 0。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 复制和交换习惯用法与移动操作之间的交互
- 像union_这样的 Boost.Geometry 操作如何处理浮点类型的基本不精确性?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- 无法合并生成操作.. 先决条件不同