我制作了这段代码,它会显示用户输入的所有正整数输入的乘积,但输出是错误的

I made this code where it will display the product of all positive integer inputs inputted by the user, but the output is wrong

所以我们的任务是创建一个程序,它会询问用户一个正整数,直到用户输入一个非正数或零,然后显示所有正输入的乘积。使用函数原型。一切正常,但是显示的输出是错误的。我猜这与我使用的公式有关,但我无法弄清楚。有人可以帮我吗?

#include <iostream>

using namespace std;

int accept_number(){
    int x;
    cin >> x;
    return x;
}

bool ispositive(int x){
    if (x > 0)
        return true;
    else
        return false;
}

int product(int x, int y){
    return (x*y);
}

void display (int a){
    cout << "The product is " << a << ".";
}

int main(){
    int userNum, total = 1;

    do {
        cout << "Enter a number: ";
        userNum = accept_number();
        total += product(userNum, total);
    } while (ispositive(userNum));

    cout << endl;
    display(total);
    cout << endl;

    return 0;
}

问题是语句:

total += product(userNum, total);

在上面的语句中,您在 total 中添加了调用 product 返回的结果。而且,不需要调用函数product。您可以直接将 totaluserNum 相乘,如下所示:

//---vv----------->also note the * instead of +
total*= userNum; //there is no need to call any function 

Working demo

我认为您的代码存在两个小问题:

  1. 你想要所有正数的乘积,我没理解错吧?那为什么是 total += product(userNum, total); 行呢?这将计算最后输入的数字与总数之间的乘积,然后 add 将其添加到总数中。如果你只需要产品,你应该覆盖总计,而不是用产品更新它,比如total = product(userNum, total),或者直接total *= userNum;

  2. 在 do-while 循环中,在 while 级别检查语句。这意味着只有在乘积考虑了负数后,循环才会退出。您可以在更新 total 之前添加一个 if 语句,然后使用 break 或类似的东西直接退出您的循环,实际上这是编码风格的问题。

假设您在程序开头输入 2。现在您期望总数为 2 (2*1 = 2)。但是你所做的,情况并非如此:

total += product(userNum, total);

..在这种情况下替换值:

1 += product(2, 1);

..这是 3。你正在做的是将 userNumtotal 的乘积添加到 total,根据问题,这不是你想要的在这里做。试试这个:

total *= userNum; // can also be written as total = total * userNum

另外,你的代码循环是错误的。为什么?因为如果你输入一个负数,它会乘以total,然后退出循环,这将导致不正确的结果。所以你应该这样重组你的循环:

int userNum = 1, total = 1; // initialize userNum = 1

do {
    total *= userNum; // this was the last instruction previously
    cout << "Enter a number: ";
    userNum = accept_number();

} while (ispositive(userNum));