5 c algorithm operators modular-arithmetic
我正在解决一个问题:用户输入3个树高和树高限制.然后程序计算要删除的树的数量.
样本输入:
Tree1: 14
Tree2: 7
Tree3: 16
Tree limit: 11
Run Code Online (Sandbox Code Playgroud)
样本输出:
Amount to remove: 8
Run Code Online (Sandbox Code Playgroud)
这对我来说通常不会太糟糕,虽然我还是初学者,但问题是,我将在没有if语句的情况下计算它.我必须使用Modulus来计算.我花了很长时间研究和尝试不同的东西,但我似乎无法得到它?有任何想法吗?
您正在寻找的表达方式是:
tree[i] % max % tree[i];
Run Code Online (Sandbox Code Playgroud)
当tree[i]大于max:
例如:16和11
16 % 11 = 5
5 % 16 = 5
Run Code Online (Sandbox Code Playgroud)
但是当tree[i]小于max:
例如:7和11
7 % 11 = 7
7 % 7 = 0
Run Code Online (Sandbox Code Playgroud)
int main(void)
{
int tree[3] = {0};
int max = 0;
int cut = 0;
printf("Max Height: "),
scanf("%d", &max);
for(int i=0; i<3; ++i)
{
printf("Tree%d: ",i+1),
scanf("%d", &tree[i]);
}
for(int i=0; i<3; ++i)
{
cut += (tree[i] % max) % tree[i];
}
printf("Amount to remove: %d\n", cut);
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在2015年8月(距离原始帖子近2年),我决定重新审视这个问题,并提出一个通用的解决方案.
它看起来有点工作,但完整的表达是:
int cut = (tree % max % tree) + !!(tree/max) * (tree/max - 1) * max;
Run Code Online (Sandbox Code Playgroud)
例子:
| Tree | Max | Expression | Answer |
| 4 | 11 | 0 + 0 * -1 * 11 | 0 |
| 47 | 11 | 3 + 1 * 3 * 11 | 36 |
Run Code Online (Sandbox Code Playgroud)
注意:我用!! (double-not)几乎只是一个C/C++构造.可能无法使用其他语言.
这是一般解决方案:
#include <stdio.h>
#define CUTAMOUNT(tr, lim) (tr - lim) * (((2 * tr) - ((2 * tr) % (tr + lim))) / (tr + lim - 1))
int main (int argc, char **argv) {
int tree1 = 14;
int tree2 = 7;
int tree3 = 16;
int limit = 11;
int cutamounttotal = 0;
cutamounttotal += CUTAMOUNT(tree1, limit);
cutamounttotal += CUTAMOUNT(tree2, limit);
cutamounttotal += CUTAMOUNT(tree3, limit);
printf("Amount to remove: %d\n", cutamounttotal);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
只有算术运算.诀窍是要理解%是唯一可以创建步骤的算术运算符.操作数必须适当调整大小,以确保步骤只发生在我们想要的地方,而不是其他地方.然后我们可以利用该步骤来提供所需的结果.