2012-06-12 50 views
-2

以下是我的代碼。我的算法有問題。它顯示來自輸入文件的最大值和最小值的整數值。值。請有人看看並告訴我我做錯了什麼?如何顯示從文件讀取的整數的最小值和最大值?

#include "cstdlib" 
#include "iostream" 
#include "fstream" 

using namespace std; 

int main() 
{ 
    fstream instream; 
    ofstream outstream; 
    instream.open("num.txt"); 
    if(instream.fail()) 
    { 
     cout<<"The input file failed to open\n"; 
     exit(1); 
    } 
    outstream.open("output.txt"); 
    if(outstream.fail()) 
    { 
     cout<<"The output file failed to open"; 
     exit(1); 
    } 

    int next, largest, smallest; 
    largest = 0; 
    smallest = 0; 

    while(instream>>next) 
    { 
     largest = next; 
     smallest = next; 
     if(largest<next) 
     { 
      largest = next; 
     } 
     if(smallest>next) 
     { 
      smallest = next; 
     } 
    } 

    outstream<<"The largest number is: "<<largest<<endl; 
    outstream<<"The smallest number is: "<<smallest<<endl; 
    instream.close(); 
    outstream.close(); 
    return 0; 
} 
+0

你調試? –

+3

另外,請修正格式。 –

+1

請查看您的問題的[格式不同](http://stackoverflow.com/posts/10993666/revisions)。下次確定你自己做這個。 @jrok,你可能不想修復問題中的代碼。 – Bart

回答

1

問題出現在這個循環中嗎?

while(instream>>next) 

    { 

    largest = next; 

    smallest = next; 

    if(largest<next) 

    { 

    largest = next; 

    } 

    if(smallest>next) 

    { 

     smallest = next; 

    } 

    } 

如果2條語句不可達,因爲最大和最小都等於next?如果while中的2 if語句從未執行,則每次迭代時最大和最小值總是被設置爲next。

+0

謝謝,我明白了。 –

2

你無條件地在每次迭代next值分配給largestsmallest

while(instream>>next) 
    { 
     largest = next; // <-- Why are you surprised? 
     smallest = next; // <-- :) 
     if(largest<next) 
     { 
      largest = next; 
     } 
     if(smallest>next) 
     { 
      smallest = next; 
     } 
    } 
2

程序往往會做什麼,他們被告知。這就是你要做的:

while(instream>>next) { 
     largest = next; 
     smallest = next; 

這是你總是將它們設置爲最新的地方。也許改變這些三線這樣的:

largest = 0; 
smallest = –0; 
while(instream>>next) { 
0
#include<cstdlib> 
#include<iostream> 
#include<fstream> 

using namespace std; 

int main() 
{ 
    fstream instream; 
    ofstream outstream; 
    instream.open("joy.txt"); 
    if(instream.fail()) 
    { 
     cout<<"The input file failed to open\n"; 
     exit(1); 
    } 
    outstream.open("output.txt"); 
    if(outstream.fail()) 
    { 
     cout<<"The output file failed to open"; 
     exit(1); 
    } 

    int next, largest, smallest; 
    largest = 0; 
    smallest = 0; 


    while(instream>>next) 
    { 

     if(largest<next) 
     { 
      largest = next; 
     }else{ 
        smallest = next; 
     } 
    } 

    outstream<<"The largest number is: "<<largest<<endl; 
    outstream<<"The smallest number is: "<<smallest<<endl; 
    instream.close(); 
    outstream.close(); 

    system("pause"); 
    return 0; 
} 
相關問題