2016-09-25 10 views
0

目標:3ダイスとリターンソートのソート構造体ソートされた構造体をメイン関数に戻すにはどうすればよいですか?

#include <stdio.h> 
#include <string.h> 
#include <time.h> 

構造体

struct RolledDice 
{ 
    int die1 ; 
    int die2 ; 
    int die3 ; 
} dice; 

プロトタイプ

void sort_dice(struct RolledDice dice); 

メイン

int main() { 
srand (time(NULL)); 

dice.die1 = rand() % 6 + 1 ; 
dice.die2 = rand() % 6 + 1 ; 
dice.die3 = rand() % 6 + 1 ; 

sort_dice(dice); 

return 0; 
} 

ソートダイス機能

void sort_dice(struct RolledDice dice) { 

    printf("Die 1: %d \n", dice.die1); 
    printf("Die 2: %d \n", dice.die2); 
    printf("Die 3: %d \n\n", dice.die3); 

    int tempDie = 0; 

は(これを行うには良い方法があるかもしれません......これは私が思い付くことが最高です)

while (dice.die1 < dice.die2 || dice.die1 < dice.die3 || dice.die2 < dice.die3) 
    { 
     if (dice.die1 < dice.die2) 
     { 
     tempDie = dice.die1 ; 
     dice.die1 = dice.die2 ; 
     dice.die2 = tempDie ; 
     } 
     if (dice.die1 < dice.die3) 
     { 
     tempDie = dice.die1 ; 
     dice.die1 = dice.die3 ; 
     dice.die3 = tempDie ; 
     } 
     if (dice.die2 < dice.die3) 
     { 
     tempDie = dice.die2 ; 
     dice.die2 = dice.die3 ; 
     dice.die3 = tempDie ; 
     } 
    } 

    printf("Die 1: %d \n", dice.die1); 
    printf("Die 2: %d \n", dice.die2); 
    printf("Die 3: %d \n\n", dice.die3); 
} 

は私が変えてみましたvoidintstructがエラーを起こしているか、またはmainstructを更新しませんでした。

答えて

2

dice構造体のコピーをソートしていますが、この構造体は、関数が返ってきたら範囲外になるとすぐに失われます。

にあなたの関数を変更

struct RolledDice sort_dice(struct RolledDice dice) { 

と最後だけreturn dice

使用量:

int main() { 
srand (time(NULL)); 

dice.die1 = rand() % 6 + 1 ; 
dice.die2 = rand() % 6 + 1 ; 
dice.die3 = rand() % 6 + 1 ; 

dice = sort_dice(dice); 

// print the sorted struct here 
printf("Die 1: %d \n", dice.die1); 
printf("Die 2: %d \n", dice.die2); 
printf("Die 3: %d \n\n", dice.die3); 
return 0; 
} 

またはポインタとしてdiceを渡し、あなたの関数でdice->代わりのdice.を使用(重いリファクタリングではあるがメモリコピーが少なく、パフォーマンスが向上する)

void sort_dice(struct RolledDice *dice) { 
... 
dice->die1 = dice->die3 ; 
... 

用法:

int main() { 
srand (time(NULL)); 

dice.die1 = rand() % 6 + 1 ; 
dice.die2 = rand() % 6 + 1 ; 
dice.die3 = rand() % 6 + 1 ; 

sort_dice(&dice); // pass as pointer so it can be modified in the function 

// print the sorted struct here 
printf("Die 1: %d \n", dice.die1); 
printf("Die 2: %d \n", dice.die2); 
printf("Die 3: %d \n\n", dice.die3); 
return 0; 
} 

注:元のコードが正しく内のあなたのソート・ルーチンバブルソート値を出力します。私は、問題はあなたが呼び出し元の関数(ソートされた値を印刷するだけの関数を作成する関数を作成することは役に立たない)を更新する方法を見つけられなかったと仮定します。

+0

私はあなたが提案した最初のオプションを試しましたが、私がメインに戻るときにソートされたバージョン。ランキングを決めるために、これらのダイスを別の関数に渡す必要があります(これは、最小から最小までソートする必要があります)。 2番目のバージョンを試してみるのに少し時間がかかります... – Ellejota

+0

私のコードを2番目のバージョンに更新しました。それは完全に動作します。ご助力ありがとうございます。あなたは素晴らしいです:)また、私はそれを理解することができたあなたの返信を簡単にしてくれてありがとう....大いに感謝! – Ellejota

+0

ありがとう! BTW私はちょうど最初のバージョンをテストし、それは動作しますが、それ以外の場合は 'dice = sort_dice(dice);'が動作しない場合は、 'dice'を呼び出す必要があります。たぶんあなたはそれを見落としました。とにかく、第2版はより効果的なので、良い選択です。 –

関連する問題