我如何编写一个程序来计算一个数字与我输入的另一个数字不同的数字的乘积?
How do i write a program that calculates the product of a number's digits that are different from another number i input?
我必须输入 2 个数字 n 和 k,然后计算 n 与 k 不同的数字的乘积。
例子:n = 1234,k=2,乘积应该是1 * 3 * 4;
#include <iostream>
using namespace std;
int main()
{
int n, k, p=1, digit;
cin >> n >> k;
while(true){
digit= n % 10;
if(digit != k){
p = p * digit;
}
n = n/10;
}
cout << "Product of digits different from K is: " << p;
return 0;
}
当我 运行 它时,在我输入 n 和 k 之后,程序不会做任何其他事情,只是保持控制台打开而没有输出。
问题是while(true)
。这样程序就永远处于循环中。
一个可能的解决方案是:
int main()
{
int n, k, p=1, digit;
cin >> n >> k;
while( n > 0 ){
digit= n % 10;
if(digit != k){
p = p * digit;
}
n = n/10;
}
cout << "Product of digits different from K is: " << p;
return 0;
}
我必须输入 2 个数字 n 和 k,然后计算 n 与 k 不同的数字的乘积。 例子:n = 1234,k=2,乘积应该是1 * 3 * 4;
#include <iostream>
using namespace std;
int main()
{
int n, k, p=1, digit;
cin >> n >> k;
while(true){
digit= n % 10;
if(digit != k){
p = p * digit;
}
n = n/10;
}
cout << "Product of digits different from K is: " << p;
return 0;
}
当我 运行 它时,在我输入 n 和 k 之后,程序不会做任何其他事情,只是保持控制台打开而没有输出。
问题是while(true)
。这样程序就永远处于循环中。
一个可能的解决方案是:
int main()
{
int n, k, p=1, digit;
cin >> n >> k;
while( n > 0 ){
digit= n % 10;
if(digit != k){
p = p * digit;
}
n = n/10;
}
cout << "Product of digits different from K is: " << p;
return 0;
}