繁体   English   中英

编写一个完整的程序,从用户那里读取 3 个数字,并计算和显示仅正整数的乘积

[英]write a complete program that will read 3 NUMBers from user and calculates and displays the product only of the positive integers

这是我迄今为止尝试过的

// Calculate the product of three integers 
#include <iostream> // allows program to perform input and output

using namespace std;

// function main begins program execution 
int main()
{
    int x; // first integer to multiply 
    int y; // second integer to multiply 
    int z; // third integer to multiply 
    int result; // the product of the three integers 
    cout << "Enter three integers: "; // prompt user for data 
    cin >> x >> y >> z; 
    result = x * y * z; 
}

我能做些什么来解决这个问题?

编辑:如果您不需要它循环使用 if 而不是 while。

看起来你需要研究一些条件语句试试:

result = x*y*z;
while(result < 0){
   cout << "Enter three integers: "; // prompt user for data 
   cin >> x >> y >> z; 
}
cout << result << endl;

应该可以正常工作...

我建议使用条件来检查输入本身的数字:

#include <iostream>

int main() {
    int inum1 = 0;
    std::cin >> inum1;
    if (inum1 < 0) { inum1 = 1; }
    int inum2 = 0;
    std::cin >> inum2;
    if (inum2 < 0) { inum2 = 1; }
    int inum3 = 0;
    std::cin >> inum3;
    if (inum3 < 0) { inum3 = 1; }
    std::cout << inum1*inum2*inum3 << "\n";
    return 0;
}

请注意,在我的示例中,我使用了 std::cout 和 std::cin 而不是using namespace std

如果您是初学者或程序很小,则使用using namespace std很好,但不鼓励大型程序使用:)

如果您发现键入std::很乏味,您可以改为包含以下语句:

using std::cin;
using std::cout;

此外,对于快速 I/O, printfscanf通常优于cincout

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM