将数字相乘

时间:2020-04-15 09:15:00

标签: c++

我要构建以下程序:

用户必须在100到999之间插入一个数字(例如100 < i < 999),并且数字必须彼此相乘。 示例:

  • 有效输入:178
  • 对应结果:1 * 7 * 8 = 72

我试图实现第一部分,即通过以下两种方式检查输入的数字是否在100和999之内,但是我的方法并不是很优雅:

#include <stdio.h>
int main()
{
    char n[4];    
    scanf("%s", n);
    printf("%d\n", (n[0]-'0')*(n[1]-'0')*(n[2]-'0'));
    return 0;
}

#include<stdio.h>
int main()
{
    int array[3];
    scanf("%1d%1d%1d", &array[0],&array[1],&array[2]);
    for ( int i=0; i<3; i++) {
        printf("%d\n", array[i]);
    }        
    return 0;
}

他们有没有更好的方法来实现相同目标?

我正在寻找C ++解决方案。

3 个答案:

答案 0 :(得分:1)

您可以在一段时间内强加std::cin作为条件:

int x;
while (std::cin >> x && x>=100 && x <=999)
\\ Do what you want

要乘以数字,只需将每个数字除以10即可得到余数,然后将其乘以当前乘积(设置一个变量,初始值为1),然后在循环中除以10,直到得出乘积即可的所有数字。例如,创建一个函数,该函数返回数字的数字乘积:

int digitproduct(int x) 
{  int product = 1;
   while (x != 0)   
   {
        product *= (n % 10);
        x /= 10; 
    } 
    return product; 
} 

在while内调用它:

int x;
while (std::cin >> x && x>=100 && x <=999)
{   cout<< digitproduct(x);
    break;
}

答案 1 :(得分:0)

人们可能会说,您的解决方案并不优雅,因为如果您想添加更多摘要或删除一些摘要,就很难轻松扩展。
用户输入超过4个字符后,第一个缓冲区也会溢出!
但出于我的选择,我非常喜欢第二个,因为它比通过int n; std::cin >> n;读取数字,对其进行验证然后计算结果显示出对C的更好的理解。

但是也有一个小缺陷,您需要检查scanf的返回值,以检测数字是否已成功解析。

int res = scanf("%1d%1d%1d", &array[0],&array[1],&array[2]);
if(res != 3) {
   printf("Invalid number format. Expected a three digit number, but got %d", res);
   return 0;
}

答案 2 :(得分:0)

更优雅的解决方案是将数字获取为整数,然后通过除法和取模运算将其分解为单个数字。

这大大提高了验证输入数字的能力,并且如果数字不是字符串形式而是其他数字形式,那么知道如何分解整数可能很有用。

示例代码:

#include <stdio.h>

int main() {
    int number;
    scanf("%d", &number);

    if(number > 999 || number < 100) {
        printf("Number not in range\n");
        return -1;
    }

    printf("%d\n",
            (number / 100) *        // hundreds digit
            (number / 10 % 10) *    // tens digit
            (number % 10)           // units digit
    );

    return 0;
}
相关问题