首页 > 解决方案 > 计算 4 位数字中特定数字 (1) 的数量

问题描述

我正在尝试制作一个程序,它要求用户输入 4 位数字,然后程序将准备好数字“1”在所选数字中重复多少次。我不知道如何让程序读取 1 的数量然后输出数量,请问有什么想法吗?谢谢你。

#include <iostream>
using namespace std;

int main() {

    int num;

    cout << "Ingrese un numero de 4 digitos porfavor. " << endl; //Enter a 4 digit number
    cin >> num;

    if (num > 999 & num < 10000) {
        // count how many 1's the number has

    } else {
        cout << "El numero que usted ha ingresado no tiene unicamente 4 digitos." << endl; //The number you chose doesnt have only 4 digits. (more/less than)
    }


}

标签: c++

解决方案


最简单的做事方式

#include <iostream>
using namespace std;

int main()
{
    int num, temp, rem, count = 0;
    cout << "Enter 4 digit number:";
    cin >> num;
    temp = num;
    while (temp != 0)
    {
        rem = temp % 10;
        if (rem == 1)
        {
            count++;
        }
        temp = temp / 10;
    }
    cout << "The number of 1 in the four digit number " << num << " = " << count;
    return 0;
}
 

推荐阅读