我基本上有一些变量
0 < na < 250
0 < max <= 16
nb = (na + max - 1) / max
n具有以下特征
0 <= i < nb - 1 => n = max
i = nb - 1 => n = na - i * max
没有三元运算符,有没有简单的方法可以做到这一点?
for (i = 0; i<nb;i++) {
n = ((i + 1) * max > na ? na - (i * max) : max);
}
实施例
na = 5
max = 2
nb = 3
i = 0 => n = 2
i = 1 => n = 2
i = 2 => n = 1
na = 16
max = 4
nb = 4
i = 0 => n = 4
i = 1 => n = 4
i = 2 => n = 4
i = 3 => n = 4
na = 11
max = 3
nb = 4
i = 0 => n = 3
i = 1 => n = 3
i = 2 => n = 3
i = 3 => n = 2
答案 0 :(得分:4)
问题不是很清楚。也许你正在寻找这样的东西:
for (i=0;i < nb;++i)
{
n = i < nb - 1 ? max : (na - 1) % max + 1;
}
答案 1 :(得分:2)
您无需计算nb。这是你可以做到的一种方式(C#):
int na = 11;
int max = 4;
for (int i = 0, x = 0; x < na; i++, x += max)
{
int n = Math.Min(max, na - x);
Console.WriteLine("i = {0}, n = {1}", i, n);
}
输出:
i = 0, n = 4
i = 1, n = 4
i = 2, n = 3
答案 2 :(得分:1)
只是为线程添加更多混淆:
如果只在前两种情况下打印最大值,那么您可以执行以下操作:(不是使用任何特定语言)
//for 0
printf("i = %d, n = %d\n",i,max)
//for 1
printf("i = %d, n = %d\n",i,max)
//for the rest
for (i = 2; i<nb;i++) {
printf("i = %d, n = %d\n",i,na - (i * max));
}
您可以避免操作员执行两个for循环
for (i = 0; (i + 1) * max) > na AND i < nb;i++) {
printf("i = %d, n = %d\n",i,0);
}
for (; i<nb;i++) {
printf("i = %d, n = %d\n",i,na - (i * max));
}