2014-04-09 4 views
0

숫자와 n 값을 취하고 그 숫자 내에서 n 개의 연속 된 숫자로 된 모든 제품을 인쇄하고 그 중 가장 큰 제품을 인쇄하려고하는 중입니다. 그들 모두.숫자 내 n 연속 정수의 인쇄 제품

예를 들어, 제약 3 12,345,043의 출력이 될 것이다 :

1 x 2 x 3 = 6 
2 x 3 x 4 = 24 
3 x 4 x 5 = 60 
4 x 5 x 0 = 0 
5 x 0 x 4 = 0 
0 x 4 x 3 = 0 
Largest product is 60 

내 코드 비정상적 수행하고 제품으로 어떤 이유로 인쇄에 (겉보기) 랜덤 값. 나는 버그를 보지 못해 누군가가 그것을 지적 할 수 있다면 매우 환영 할 것입니다.

1 x 2 x 3 = 124950 
2 x 3 x 4 = 132600 
3 x 4 x 5 = 140556 
4 x 5 x 0 = 132288 
5 x 0 x 4 = 132288 
0 x 4 x 3 = 127296 
The greatest product is 140556 

당신은 매우 부적절한 출력을 볼 수 있듯이 :

#include <iostream> 
#include <string> 

using namespace std; 

int findProducts (string num, int cap); //Function to find all products and highest product 

int main() 
{ 
    string num = "12345043"; //Input 
    int constraint = 3; //Number of multiples per equation 
    int prod = findProducts(num, constraint); //Function to find all products and highest product 
    cout << "The greatest product is " << prod << endl; 
    return 0; 
} 

int findProducts (string num, int cap) //Function to find all products and highest product 
{ 
    int product = 1; //Product 
    int max = 0; //Variable to keep track of largest product 
    for (int i = 0; i < num.length() - (cap - 1); i++) //Loop to go through all numbers in string input 
    { 
     for (int j = 0; j < cap; j++) //Loop through until the number of variables printed is equal to the constraint 
     { 
      product*=num[i + j]; //Make product equal to itself times num[i + j] 
      cout << num[i + j]; 
      if (j != cap - 1) //If statement to cap extraneous x's being printed 
      { 
       cout << " x "; 
      } 
     } 
     cout << " = " << product << endl; 
     if (max < product) //If statement to check if the new product is the highest product 
     { 
      max = product; 
     } 
     product = 1; //Reset product 
    } 
    return max; //Return the highest product 
} 

다음은 위의 코드 내 출력됩니다.

다시 한번 도움을 주시면 감사하겠습니다. 당신은 그 문자를 변환해야

product *= num[i + j];

:

감사합니다, 트리스탄

답변

0

문제는 당신이 입력 문자열의 숫자에 해당하는 문자으로 product를 곱하여하고 있다는 것입니다 먼저 해당 숫자로 이동하십시오. 당신은 그런 일에이 작업을 수행 할 수 있습니다

product *= num[i + j] - '0';

나는 그것을 테스트하고 변경 후, 프로그램은 올바른 출력을 제공합니다.

+0

내가 그 것을 알아 채지 못했다고 나는 믿을 수 없다. 나는 그런 바보 같이 느낀다. 고마워요! – Tristan