[英]C++ I need to check if a two-digit number contains a 0 or not
我正在制作一个程序,我需要检查像 76 或 70 这样的两位数是否包含 0。
76
结果将是错误的70
真我似乎无法编造一些东西,而且我仍然被困在不知道如何开始的事情上。
您可以将数字转换为字符串并检查第一个或第二个字符是否为“0”
bool containsZero (int x) {
string tmp = to_string(x);
if (tmp[0] == '0' || tmp[1] == '0')
return true;
return false;
}
或将 10 上的数字除以两次并检查每个数字是否为 0
bool containsZero (int x) {
while (x != 0)
{
if (x % 10 == 0)
return true;
x = x / 10;
}
return false;
}
唯一包含零的两位数是那些能被 10 整除的数,所以
bool has_zero = number % 10 == 0;
假设数字是x
您可以使用以下条件轻松检查两位数:
if((x%10==0)||(x/10)%10==0))
{
//number has zero
}
else
{
//number does not have zero
}
如果它仅用于两位数,您可以在返回参数为布尔值的函数中执行以下操作:
bool contains_zero(int num) {
int rem = num % 10;
return rem == 0;
}
如果你想逐位检查,那么初始逻辑可能是:
#include <iostream>
#include <string>
using namespace std;
int main() {
bool ischeck = false;
int x = 67;
string a = to_string(x);
for(int i=0;i <a.length();i++)
{
if(a[i]=='0')
{
ischeck = true;
break;
}
}
if(ischeck)
{
cout<<"True\n";
}
else{
cout<<"False\n";
}
}
否则@freakish 解释的逻辑是最好的。 在那种情况下,程序将是
#include <iostream>
#include <string>
using namespace std;
int main() {
int x = 70;
if(x%10==0)
{
cout<<"True";
}
else{
cout<<"False";
}
}
第二种逻辑不适用于像“05”或“07”这样的数字,但第一种逻辑适用于任何情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.