2011-08-06 5 views
2

プログラムでは、double型の配列の要素を埋める関数を作成し、別の関数show()を使用して表示する必要があります。今、1,2,3,4,5のような単純な数字を入力すると、次のようになります。 show関数はそれらの数値を表示するのではなく、8.586689e + 273のようなガベージ値を表示します。2値がcoutで表示されない

何が間違っているのか分かりません。特に、ここに別のプログラムを開いているときに数字がうまく印刷されている場合は特にそうです。ここで

はコードです:

#include<iostream> 

int fill(double arr[], int); 
void show(const double arr[], int); 
void reverse(double arr[], int); 
const int size = 5; 
using namespace std; 

int main() 
{ 
double arr[size]; 

int limit = fill(arr,size); 

show(arr,limit); 
reverse(arr,limit); 
show(arr,limit); 

return 0; 
} 

int fill(double arr[], int size) 
{ 
cout<<"Enter the values to fill the array: "<<endl; 
int i,temp; 

    for(i=0;i<size;i++){ 
     cout<<"Enter entry #"<<i+1<<" : "; 
     cin>>temp; 
     if(!cin){ 
        cin.clear(); 
        while(cin.get()!='\n') 
         continue; 
        cout<<"Bad Input.Input Process Terminated."; 
        break; 
       } 
     else if(temp<0){ 
      break; 
      arr[i]=temp; 
     } 
    } 
return i; 
} 


void show(const double ar[], int n) 
{ 
using namespace std; 
    for(int i=0;i<n;i++){ 
     cout<<"Entry #"<<(i+1)<<": "; 
     cout<<ar[i]<<endl; 
    } 
} 

void reverse(double arr[], int limit) 
{ 
    cout<<"Reversing values..."<<endl; 
    double temp; 
    for(int i=0;i<limit/2;i++){ 
     temp = arr[i]; 
     arr[i]=arr[limit-i-1]; 
     arr[limit-i-1]=temp; 
    } 
} 
+0

宿題が必要ですか? –

+0

私はちょっと言っていました...コピーされた宿題のように見えました。 –

+0

宿題ではない...私はC++ Primerという本から自分自身を教えている。 :) –

答えて

2

あなたがエリアを充填されていません。あなたがそうしようとしていた場所に注意してください。あなたは休憩声明の後で、< 0状態の中に入れます。したがって、決して実行されません。 あなたの配列は初期化されていないので(ベクトルを使うべきです)、正しく表示されない奇妙な値が含まれています。

int fill(double arr[], int size) 
{ 
cout<<"Enter the values to fill the array: "<<endl; 
int i,temp; 

    for(i=0;i<size;i++){ 
     cout<<"Enter entry #"<<i+1<<" : "; 
     cin>>temp; 
     if(!cin){ 
        cin.clear(); 
        while(cin.get()!='\n') 
         continue; 
        cout<<"Bad Input.Input Process Terminated."; 
        break; 
       } 
     else if(temp<0){ 
      break; 
     } 
     arr[i]=temp; 
    } 
return i; 
} 
+0

ありがとう...私が直面している問題のほとんどは、私の愚かな小さな間違いのためです。これは私が作業する必要があるものです。 –

1

データを配列に格納しないでください。配列にはゴミが含まれていて、ゴミが表示されます。

私はこのコードを推測している:

else if(temp<0){ 
     break; 
     arr[i]=temp; 
    } 

は...代わりにされている必要があります:

else if(temp<0){ 
     break; 
    } 
    arr[i]=temp; 
0

これはケアレスミスのほんの一例です。

else if(temp<0){ 
      break; 
      //^^^^^ After break 
      arr[i]=temp; 
      //How can you expect the next line to get executed. 
     } 
関連する問題