c++ - 计算 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)
}
}
解决方案
最简单的做事方式
#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;
}
推荐阅读
- visual-studio-code - VSCode:CTRL +右箭头触发cursorWorkEndRight,但随后被转换为cursorWordLeft
- javascript - django form.is_valid 在使用 XMLHttpRequest 时返回 false
- git - 从 Ant 迁移到 Intellij 中的 Grade 时如何保留 git 信息?
- mysql - 根据不同条件生成带有 SUM 列的表
- google-apps-script - 用于减去日期时间格式的脚本以获得以小时为单位的结果
- python - 在熊猫中创建数据透视表
- html - 如何在 React JS 中将 Button 链接到另一个页面?
- javascript - cookie-session 和 JWT 令牌有什么区别?
- kubernetes - 在 falco 中启用审计规则
- python - 如何在python中以正确的输出启动表