Cプログラミングで整数の配列を左から右に反転するにはどうすればよいですか?
#include <math.h>
#include <stdio.h>
int main() {
int k[4] = {1,2,3,4};
N=4;
for(k=1; k<=N; k=k+1);
printf("%d",flip(k));
}
例: k = [1,2,3,4] フリップは k=[4,3,2,1] を与える必要があります k は数値配列です
Cプログラミングで整数の配列を左から右に反転するにはどうすればよいですか?
#include <math.h>
#include <stdio.h>
int main() {
int k[4] = {1,2,3,4};
N=4;
for(k=1; k<=N; k=k+1);
printf("%d",flip(k));
}
例: k = [1,2,3,4] フリップは k=[4,3,2,1] を与える必要があります k は数値配列です
as として宣言N
しますint
(k
必要ありません)。残りをループで 10ずつ出力しN = N/ 10
、毎回デクリメントします。次のコードを試してください。
for(; N; N = N/10)
printf(" %d", N % 10);
ループは N != 0 まで実行されます。
番号を逆にするのではなく、逆に印刷するだけです。
まず第一に、あなたの質問は曖昧で矛盾しています。たとえば、k
質問に含めるコードが示唆するように単一の整数ですか、k
それとも「ベクトル」についての話が示唆するように整数の配列ですか? さらに、整数を反転しますか、それとも配列を反転しますか? これらは2つの非常に異なる質問です。今後の参考のために、良い答えを得たい場合は、良い質問をする必要があります。あなたの作品の一部を見せても問題ありません。
とにかく、diatribeはさておき、配列を元に戻すコードは次のとおりです。エラーチェックがないので、間違った方法で呼び出した場合... まあ、あなたは自分で:
void flip(int *array, // the array to reverse
int count) // the number of elements in the array
{
int i = 0, tmp;
while(i != count / 2)
{
tmp = array[i];
array[i] = array[count - i - 1];
array[count - i - 1] = tmp;
i++;
}
}
この関数の使用方法のサンプルについては、私が作成したこのサンプル プログラムを確認してください。
その場合、source
が現在の配列であり、 が割り当てられSIZE
たサイズの定数であり、ターゲット配列であると仮定すると、これを使用できます。source
destination
for (is = SIZE - 1, id = 0; is >= 0; is--, id++) {
destination[id] = source[is];
}
source
sの中身を入れ替えたい場合は…
逆に複製する代わりに置き換えたい場合は、これを実行してからsource
に割り当てます:destination
source
for (counter = 0; counter < SIZE; counter++) {
destination[counter] = source[counter];
}
これを試して:
int flip(int k) {
int new = 0;
while (k > 0) {
// Take the last digit and add it to the front of new
new = (new * 10) + k % 10;
// Divide by ten to drop the last digit of k
k = k / 10;
}
return new;
}