2014-10-31 3 views
0

프로젝트를 수행하려고하는데 막혔습니다. 교수님은 제가 이해한다면 동적 배열을 사용하고, 정수를 비교하여 GCD를 얻는 기능을 원합니다. 나는 기능을 작동하게 할 수 없다. 이견있는 사람? 여기에 prom :동적 배열 및 함수

유한 정수 집합의 가장 큰 공약수를 계산하는 프로그램을 작성하십시오. 함수를 사용하여 GCD를 계산하십시오. 세트의 요소 수는 미리 결정되어서는 안됩니다. 데이터를 입력 할 때 카운트 할 코드, 세트에있는 숫자의 수를 작성해야합니다. 유클리드 알고리즘을 기본으로합니다. ;

I 입력 10, 100, 40 및 GCD는 10해야하지만, 나는이 결과를 얻을 :

The GCD of: is: 
    10   0  
    100   0 
    40   0 

#include <iostream> 
#include<iomanip> 

using namespace std; 

int greatestdivisor(int b[], int size); /*Write prototype for gcd */ 

int main() 
{ 
    int greatest; 
    int max=1; 
    int* a= new int[max]; //allocated on heap 
    int n=0; 

    cout<<"Input numbers: "<<endl; 
    cout<<"Hit Enter key after each input and type any letter to finish"<<endl; 

    while(cin>>a[n]){  //read into array 
     n++; 
     if(n>=max){ 
      max=n; //increase size of array 
      int* temp = new int[max]; //creates new bigger array 

      for(int i=0;i<n;i++){ 
       temp[i] = a[i]; //copy values to new array 
      } //end for 
      delete [] a;  //free old array memory 
      a = temp;  //a points to new array 
     } //end if 

    } // end while 
    cout<<endl; 
    greatest = greatestdivisor(a, max); 
    cout<<"The GCD of: "<<" is: "<<endl; 
    for(int j=0;j<max;j++) 
     cout<<setw(5)<<a[j]<<setw(10)<<greatest<<endl; 
    n++;// prints elements of array and call function 
} // end main 

// gcd finds greatest common divisor of array 
int greatestdivisor(int b[], int size) 
{ 
    int greatest =1;// current greatest common divisor, 1 is minimum 

    for (int x=0; x<=size; x++) { 
     int m=b[x]; 
     int r=2; 
     if(m%r==0){ 
      greatest =m; // update greatest common divisor 
     } //end if 
    } // end for 
    return greatest; //return gcd 
} // end fuction gcd 
+0

처럼 뭔가 단순화'나는 기능이 작동하게 캔트.'프로그램에 무엇이 잘못 되었습니까? 자세한 내용을 제공해주십시오. – user657267

+0

실행할 때 잘못된 정보가 표시됩니다. 그것은 내가 입력 한 데이터와 함께 10을 표시해야합니다. – Meeeeee

+1

gcd 알고리즘으로 촬영하는 경우'maximumdivisor' 함수가별로 도움이되지 않는 것 같습니다. 테스트 조건은'x WhozCraig

답변

2

코드에서 많은 문제가있다, try this 그리고 무엇을 잘못하고 있는지 알아 내려고 :

#include <iostream> 
#include<iomanip> 

using namespace std; 

int greatestdivisor(int b[], int size); /*Write prototype for gcd */ 

int main() 
{ 
    int greatest; 
    int max=1; 
    int* a= new int[max]; //allocated on heap 
    int n=0; 

    cout<<"Input numbers: "<<endl; 
    cout<<"Hit Enter key after each input and type any letter to finish"<<endl; 

    while(cin>>a[n]){  //read into array 
     n++; 
     if(n>=max){ 
      max=n+1; //increase size of array 
      int* temp = new int[max]; //creates new bigger array 

      for(int i=0;i<n;i++){ 
       temp[i] = a[i]; //copy values to new array 
      } //end for 
      delete [] a;  //free old array memory 
      a = temp;  //a points to new array 
     } //end if 

    } // end while 
    cout<<endl; 
    greatest = greatestdivisor(a, n); 
    cout<<"The GCD of: "<<" is: "<<endl; 
    for(int j=0;j<n;j++) 
     cout<<setw(5)<<a[j]<<setw(10)<<greatest<<endl; 
} // end main 


int gcd(int a,int b) 
{ 
    int t; 
    while(a) 
    { 
     t = a; 
     a = b%a; 
     b = t; 
    } 
    return b; 
} 

// gcd finds greatest common divisor of array 
int greatestdivisor(int b[], int size) 
{ 
    int greatest =b[0];// current greatest common divisor, 1 is minimum 

    for (int x=1; x<size; x++) { 
     greatest = gcd(greatest, b[x]); // update greatest common divisor 
    } // end for 
    return greatest; //return gcd 
} // end fuction gcd 
2

GCD 알고리즘이 손상되었습니다. 첫 번째 두 항목부터 시작하여 어레이의 각 연속 값에 대한 GCD를 찾아야합니다. 배열의 모든 항목을 반복하면 마지막 gcd가 모든 항목에 공통으로 적용됩니다. 그리고 코멘트에서 언급했듯이, (고장난) gcd 반복 알고리즘의 크기도 잘못되었습니다. 그것은 엄격히 -보다 적어야합니다.

#include <iostream> 
#include <iomanip> 
#include <cmath> 

static int gcd(const int b[], size_t size); 

int main() 
{ 
    int* a = nullptr, value=0; 
    size_t n = 0; 

    std::cout<<"Input numbers:\n"; 
    while(std::cin >> value) 
    { 
     int *temp = new int[n+1]; 
     std::copy(a, a+n, temp); 
     delete [] a; 
     a = temp; 
     a[n++] = value; 
    } 

    std::cout<<"The GCD is " << gcd(a, n) << '\n'; 
    delete [] a; 
} 

static int gcd(const int b[], size_t size) 
{ 
    int res = (size > 0 ? std::abs(b[0]) : 0); 
    for (size_t x=1; x<size; ++x) 
    { 
     int n = std::abs(b[x]); 
     while (n > 0) 
     { 
      auto tmp = res; 
      res = n; 
      n = tmp % n; 
     } 
    } 
    return res; 
} 

출력

Input numbers: 
10 
100 
40 
x 
The GCD is 10 

세상을 더 나은 곳으로 만들기 : 이제 std::vector

아래로 많이 제거 버전은 다음과 같다 수동으로 관리되는 동적 배열이 어떻게 작동하는지 알 수 있으므로 이 아닐 경우 얼마나 간단 할 지 충분히 짐작할 수 없습니다. 처음에는 표준 라이브러리를 사용하고 단순히 표준 라이브러리의 기능을 사용합니다. std::vectorstd::istream_iterator은이 작업에 대한 간단한 작업을 수행하며 코드는 기념비적으로 오류가 발생하기 쉽습니다. std::vector에서 동적 메모리 관리를 가져오고 std::istream_iterator을 사용하여 EOF 또는 int 데이터에 형식화 된 입력 복사를 수행합니다. 즉, 거의 모든 데이터 관리 방식이 처리됩니다.

는 봐 :

#include <iostream> 
#include <vector> 
#include <iterator> 
#include <iomanip> 
#include <cmath> 

static int gcd(const int b[], size_t size); 

int main() 
{ 
    std::cout<<"Input numbers:\n"; 
    std::vector<int> a((std::istream_iterator<int>(std::cin)), 
         std::istream_iterator<int>()); 
    std::cout<<"The GCD is " << gcd(a.data(), a.size()) << '\n'; 
} 

static int gcd(const int b[], size_t size) 
{ 
    int res = (size > 0 ? std::abs(b[0]) : 0); 
    for (size_t x=1; x<size; ++x) 
    { 
     int n = std::abs(b[x]); 
     while (n > 0) 
     { 
      auto tmp = res; 
      res = n; 
      n = tmp % n; 
     } 
    } 
    return res; 
} 

출력은 이전과 동일합니다. 행운의 행운

+0

이것은 istream iterators에 대해 잘 모르겠습니다. +1 – chrisb2244

1

문제가 설명 된대로 완전히 지정되면 array이 명시 적으로 필요하지 않은 것처럼 보입니다.

는, 당신이

#include <vector> 
#include <iostream> 
#include <sstream> 

int greatestdivisor(std::vector<int> &ints); 
int euclid(int a, int b); 

int main() 
{ 
    std::vector<int> listOfInts; 
    std::string line = "default"; 
    int tempInt=0; 

    std::cout << "Description" << std::endl; 

    while (line.length() != 0) 
    { 
     std::getline(std::cin, line); 
     std::stringstream temp(line); 
    temp >> tempInt; 
    listOfInts.push_back(tempInt); 
    } 
    listOfInts.pop_back(); // Remove the last entry, which is counted twice by this while loop :/ 

    for (int i=0; i< listOfInts.size(); i++) 
    { 
     std::cout<< listOfInts[i] << std::endl; 
    } 

    int gcd = greatestdivisor(listOfInts); 
    std::cout << "gcd = " << gcd << std::endl; 
} 

int greatestdivisor(std::vector<int> &ints) 
{ 
    int currentGCD = ints[0]; 
    while (ints.size() > 0) 
    { 
    int a = ints.back(); 
    ints.pop_back(); 
    currentGCD = euclid(a, currentGCD); 
    std::cout << "currentGCD = " << currentGCD << std::endl; 
    } 
    return currentGCD; 
} 

int euclid(int a, int b) 
{ 
    if (b == 0) 
    return a; 
    else 
    return euclid(b, a % b); 
}