ページ 11

C言語 並び替え

Posted: 2014年2月01日(土) 12:00
by 崖っぷち
5つの数値を入力(繰り返し入力)し、小さい順に表示しなさい。入力したすべての値が0の場合に処理を中止します。
とゆう問題ができません><
どなたかご協力お願いします。

Re: C言語 並び替え

Posted: 2014年2月01日(土) 12:04
by 初級者
できません、というのは、
コードが全く書けないと
いうことでしょうか。

それとも、書きかけの
コードはある、ということでしょうか。

Re: C言語 並び替え

Posted: 2014年2月01日(土) 12:11
by 崖っぷち
返信ありがとうございます><
以下のプログラムを一応書いたのですが繰り返しになりません><
#include <stdio.h>


int main(void){
int i, j, n[5], min, temp;

for(i=0; i<5; i++){
printf("%2d番目の数値?", i+1);
while(scanf("%d",&n)==n)
}
for(i=0; i<5; i++){
min = i;
for(j = i + 1; j < 5; j++){
if(n[min] > n[j]) min = j;
}
temp = n[min];
n[min] = n;
n = temp;
}

printf("並べ替え後は\n");
for(j=0; j<5; j++){
printf("%2d番目\t%d\n", j+1, n[j]);
}


return 0;
}

Re: C言語 並び替え

Posted: 2014年2月01日(土) 12:19
by 初級者
データ入力時の
while文で何をしようと
しているかが
よくわかりません。

for文でもって、
繰り返しの目的は
達成できているの
ではないでしょうか。

Re: C言語 並び替え

Posted: 2014年2月01日(土) 12:21
by 崖っぷち
すみません;;
ミスです。
書き直しました。
#include <stdio.h>


int main(void){
int i, j, n[5], min, temp;

for(i=0; i<5; i++){
printf("%2d番目の数値?", i+1);
scanf("%d",&n);
}
for(i=0; i<5; i++){
min = i;
for(j = i + 1; j < 5; j++){
if(n[min] > n[j]) min = j;
}
temp = n[min];
n[min] = n;
n = temp;
}

printf("並べ替え後は\n");
for(j=0; j<5; j++){
printf("%2d番目\t%d\n", j+1, n[j]);
}


return 0;
}

Re: C言語 並び替え

Posted: 2014年2月01日(土) 12:31
by 崖っぷち
めんどくさいやり方なら一応できたんですけど・・・これをさらにコンパクトにしたくて・・・
#include<stdio.h>

void sori(int &x,int &y)
{ int temp;
if(x>y) {
temp=x; x=y;
y=temp;
}
return;
}
int main(void)
{ int a,b,c,d,e;
while(scanf("%d,%d,%d,%d,%d",&a,&b,&c,&d,&e)==5) {
if(a==0&&b==0&&c==0&&d==0&&e==0) break;
sori(a,b);
sori(a,c);
sori(a,d);
sori(a,e);
sori(b,c);
sori(b,d);
sori(b,e);
sori(c,d);
sori(c,e);
sori(d,e);
printf("小さい順に→%d,%d,%d,%d,%d",a,b,c,d,e);
}
return(0);
}

Re: C言語 並び替え

Posted: 2014年2月01日(土) 14:27
by 初級者
12時21分のコードの方が
マシな気がします。ちゃんと動くのならば。

最後のコードは、ダメダメです。
そもそも、ビルドできますか?
データが5個なら、sort()の呼び出しが15行
10個なら55行。20個なら210行。
そんなにズラ〜っと書くのは
ナンセンスです。
12時21分の方がマシと書いたのは、
少なくともループで制御している分だけ
マシ、という意味です。

Re: C言語 並び替え

Posted: 2014年2月01日(土) 14:39
by 初級者
12時21分のコードに
5個のデータが全部0ならば、プログラムを終了する
というロジックを加えることはむずかしいですか?

Re: C言語 並び替え

Posted: 2014年2月01日(土) 15:58
by みけCAT
コードを提示するときはBBcodeを有効にした状態でcodeタグで囲み、
かつ適切なインデントをしていただけると、見やすくて助かります。

Re: C言語 並び替え

Posted: 2014年2月01日(土) 16:00
by みけCAT
崖っぷち さんが書きました:めんどくさいやり方なら一応できたんですけど・・・これをさらにコンパクトにしたくて・・・
#include<stdio.h>

void sori(int &x,int &y)
{ int temp;
if(x>y) {
temp=x; x=y;
y=temp;
}
return;
}
int main(void)
{ int a,b,c,d,e;
while(scanf("%d,%d,%d,%d,%d",&a,&b,&c,&d,&e)==5) {
if(a==0&&b==0&&c==0&&d==0&&e==0) break;
sori(a,b);
sori(a,c);
sori(a,d);
sori(a,e);
sori(b,c);
sori(b,d);
sori(b,e);
sori(c,d);
sori(c,e);
sori(d,e);
printf("小さい順に→%d,%d,%d,%d,%d",a,b,c,d,e);
}
return(0);
}
これはC言語ではなくC++ですね。タイトルに合っていません。

Re: C言語 並び替え

Posted: 2014年2月01日(土) 16:02
by みけCAT
ヒントを与えておきます。
[search=google]qsort[/search]

Re: C言語 並び替え

Posted: 2014年2月02日(日) 00:42
by 崖っぷち
沢山のご指摘ありがとうございます。
C言語初めてまだ3ヶ月とゆう初心者とも呼べないノミみたいなレベルなのでこんな質問したことをお許し下さい。