在一个数字内打印n个连续整数的乘积

时间:2014-04-09 23:17:39

标签: c++ numbers product

我试图修改一个带有数字和n值的程序并打印出该数字中n个连续数字的所有产品,然后打印出所有这些产品中最好的产品。

例如,约束为3的12345043的输出为:

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

我的代码执行异常,并且由于某种原因打印(看似)随机值作为产品。我似乎无法看到这个错误,如果有人能指出它会非常受欢迎。

#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
}

以下代码是我的输出:

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

正如您所看到的,非常不正确的输出。

再次,非常感谢任何帮助。

谢谢, 特里斯坦

1 个答案:

答案 0 :(得分:0)

问题是,您要将product乘以与输入字符串中的数字对应的字符

product *= num[i + j];

您必须先将该字符转换为相应的数字。你可以这样做:

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

我测试了它,在更改之后,程序提供了正确的输出。