Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 打印一个数内n个连续整数的乘积_C++_Numbers_Product - Fatal编程技术网

C++ 打印一个数内n个连续整数的乘积

C++ 打印一个数内n个连续整数的乘积,c++,numbers,product,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 我的代码执行异常,出于某种原因,会打印(似乎)随机值作为产品。我似乎看不到这个bug,所以如果有人能指出它,那将是非常受

我正试图纠正一个程序,它将接受一个数字和一个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
我的代码执行异常,出于某种原因,会打印(似乎)随机值作为产品。我似乎看不到这个bug,所以如果有人能指出它,那将是非常受欢迎的

#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
}
如您所见,输出非常不正确

再次感谢您的帮助

谢谢,
Tristan

问题在于,您将
产品
乘以与输入字符串中的数字对应的字符

product*=num[i+j]

您必须首先将该字符转换为相应的数字。您可以使用类似的方法来执行此操作:

product*=num[i+j]-“0”


我对它进行了测试,更改后,程序给出了正确的输出。

我真不敢相信我没有注意到,我觉得自己像个白痴。非常感谢你!
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