List C+中列表中所有元素的乘法之和+;

List C+中列表中所有元素的乘法之和+;,list,stl,List,Stl,假定程序返回列表中所有元素的乘法之和。 如果列表包含(1,2,3),则应返回6。 我看到了一些相关的帖子,但我还是不明白 我试过这个: 第xList cotains(3,2) for(std::list::iterator it=xList.begin();it!=xList.end();+it) { 小计=(*it)*(*it+1)); 总计=总计+小计; } 我得到的输出是18,我应该得到6。有什么线索吗?你的问题是这行: for (std::list<unsigned>::i

假定程序返回列表中所有元素的乘法之和。 如果列表包含(1,2,3),则应返回6。 我看到了一些相关的帖子,但我还是不明白

我试过这个:

第xList cotains(3,2)

for(std::list::iterator it=xList.begin();it!=xList.end();+it)
{
小计=(*it)*(*it+1));
总计=总计+小计;
}

我得到的输出是18,我应该得到6。有什么线索吗?

你的问题是这行:

for (std::list<unsigned>::iterator it=xList.begin(); it!=xList.end(); ++it)
{
    subtotal= ((*it) * (*(it+1));

    total= total + subtotal;
}
小计=((*it)*(*it+1));

您正在取消对指针的引用,然后向其添加一个指针,但要做的是向指针添加一个指针:


小计=((*it)*(*(it+1));

您的问题是这一行:

小计=((*it)*(*it+1));

您正在取消对指针的引用,然后向其添加一个指针,但要做的是向指针添加一个指针:


subtotal=((*it)*(*(it+1));

假设@Frank Osterfeld的评论正确地建议您需要列表中元素的产品,这将实现:

#include <iostream>
#include <list>

int main () {
    std::list<unsigned> xList;
    xList.push_back(3);
    xList.push_back(2);

    unsigned product = 1;

    for (std::list<unsigned>::iterator it=xList.begin(); it!=xList.end(); ++it) {
        product = product * (*it);
    }

    std::cout << product << std::endl;
    return 0;
}
#包括
#包括
int main(){
std::列表xList;
xList.push_back(3);
xList.push_back(2);
无符号乘积=1;
对于(std::list::iterator it=xList.begin();it!=xList.end();++it){
产品=产品*(*it);
}

std::cout假设@Frank Osterfeld的评论正确地建议您需要列表中元素的乘积,这将实现:

#include <iostream>
#include <list>

int main () {
    std::list<unsigned> xList;
    xList.push_back(3);
    xList.push_back(2);

    unsigned product = 1;

    for (std::list<unsigned>::iterator it=xList.begin(); it!=xList.end(); ++it) {
        product = product * (*it);
    }

    std::cout << product << std::endl;
    return 0;
}
#包括
#包括
int main(){
std::列表xList;
xList.push_back(3);
xList.push_back(2);
无符号乘积=1;
对于(std::list::iterator it=xList.begin();it!=xList.end();++it){
产品=产品*(*it);
}

std::cout此处建议的答案假设存储的输出在整数范围内!!!,如果输出将跨越2^64!!!。一个可能的解决方案是添加(列表添加,而不使用“+”运算符)可用和n次,其中n来自列表。

此处建议的答案假设存储的输出在整数范围内!!!,如果输出将跨越2^64!!!。一种可能的解决方案是添加(列表添加,而不使用“+”运算符)可用的和n次,其中n是从列表中取出来的。

我看不出你的算法是如何实现你所描述的。你的意思是total*=*它吗?(total初始化为1)是的,total初始化了。我看不到你的算法是如何实现你所描述的。你的意思是total*=*它吗?(total初始化为1)是的,总数是初始化的,包括实际代码示例可以使这个答案更好。包括实际代码示例可以使这个答案更好
#include <iostream>
#include <list>

int main () {
    std::list<unsigned> xList;
    xList.push_back(3);
    xList.push_back(2);

    unsigned product = 1;

    for (std::list<unsigned>::iterator it=xList.begin(); it!=xList.end(); ++it) {
        product = product * (*it);
    }

    std::cout << product << std::endl;
    return 0;
}