如何在C ++中添加用户输入数组中的每个第n位? [英] How to add every nth digit in a user input array in C++ ?
问题描述
c ++中的代码。
假设我输入一个数组,我想跳过每个第d位并在离开每个第d位后计算总和。然后我的代码将是?
for(i = 0; i< n; i + d)
{
add + = i; < br $>
}
我尝试过:
for (i = 0 ; i< n; i + d)
{
add + = i;
}
首先考虑老师为您设置的问题:您显示的代码将无效(a; b; d)
c; <
/ pre>
a在循环之前执行一次并允许你设置启动条件。
b每个循环执行一次以检查它是否应该循环并且执行主体(c)。
$ $ bc每次循环时执行一次。
d在(c)之后立即执行并为下一次设置条件圆形。
例如,要打印数组的五个元素:
for (i = 0 ; i< 5 ,i ++)
cout<< ; arr [i];但是一旦你初始化它,你显示的代码就不会改变
i
,所以循环永远不会结束。
如果你改写它会开始工作:
(i = 0 ; i< n; i + = d)但您仍然希望在循环内访问您的数组数据索引值...
您的代码
。
- 不访问数组。
- Doesn' t跳过每个
d
周期。
要访问数组,您可以将其编入索引:
sum + = a [i]
要跳过每个d
周期,你可以使用if
if ((i%d)!=(d- 1 ))
{
// not-skipping cod e
}
code in c++.
suppose i input an array and i want to skip every dth digit and calculate the sum after leaving every dth digit. Then my code would be ?
for(i=0;i<n;i+d)
{
add+=i;
}
What I have tried:
for(i=0;i<n;i+d)
{
add+=i;
}
Start by thinking about the problem your teacher set you: the "code" you show won't work, or even ever finish.
for (a; b; d) c;
a is executed once, before the loop and lets you set up the start conditions.
b is executed once per loop to check if it should go round and execute the body (c).
c is executed once each time the loop goes round.
d is executed immediately after (c) and sets up teh conditions for teh next time round.
For example, to print five elements of an array:
for (i = 0; i < 5, i++) cout << arr[i];But the code you show doesn't change
i
at all once you have initialised it, so the loop will never end.
It would start to work if you wrote this instead:
for (i = 0; i < n; i += d)But you would still want to access your array data inside the loop instead of the index value ...
Your code
.
- Doesn't access the array.
- Doesn't skip every
d
cycles.
To access the array you may index it:
sum += a[i]
To skip at everyd
cycle you could use anif
if ( (i % d) != (d-1) ) { // not-skipping code }
这篇关于如何在C ++中添加用户输入数组中的每个第n位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!