2012-06-12 5 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 문은 도달 할 수없는 wouldnt가 있다면? while의 2 if 문이 실행되지 않으면 가장 큰 값과 가장 작은 값이 각 반복에서 항상 다음 값으로 설정됩니다.

+0

감사합니다. –

2

당신은 무조건 반복마다에 largestsmallestnext의 값을 할당 :

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; 
} 
관련 문제