我希望用C ++计算给定字符串中的偶数。我的代码是:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int i(0), c(0), z(0), j(1), n1, x(0);
string n;
int main()
{
cout << "Hello n world!" << endl;
cin >> n; //The number itself
while (true)
{
if (( n[i] >= '0' && n[i] <= '9'))
{
x++;
}
else break;
i++;
} //Counts the numbers
cout << "The number has " << x << " digit(s)." << endl;
istringstream convert(n);
if ( !(convert >> n1) )
n1 = 0; //converts string to an int
while (c < x)
{
if ( n1 % 2 == 0 )
{
z++;
};
n1 = n1 % 10;
c++;
}; //Counts the even numbers (I can feel this part is wrong, I just don't know how)
cout << "The number has" << z << " even digit(s)." << endl;
return 0;
}
但是当我使用它时,当我输入1022时,我得到4个偶数,如果我输入696969则得到0偶数。我该怎么办?我的代码出了什么问题?
答案 0 :(得分:2)
n1 = n1/10; not %
这应解决计算偶数个数的基本逻辑。代码中可能存在其他错误。我的机器上没有C ++ - 所以无法运行它。
答案 1 :(得分:0)
在这个循环中
while (c < x)
{
if ( n1 % 2 == 0 )
{
z++;
};
n1 = n1 % 10;
c++;
};
在第一次迭代后,变量n1将始终等于最初存储在n1中的原始数字的最后一位数。
例如,如果你有数字1022
,那么在第一次迭代之后由于语句
n1 = n1 % 10;
n1
将等于2
。
在后续迭代中,n1将保留此值,因为
2 % 10 == 2
一般来说,程序的逻辑不正确。例如,如果用户输入字符串"1022A"
,则由于错误,if语句中的表达式将等于true
istringstream convert(n);
if ( !(convert >> n1) )
^^^^^^^^^^^^^^^ this will be true because "1022A" is not a number
n1 = 0; //converts string to an int
因此前一个循环
之间存在不一致while (true)
{
if (( n[i] >= '0' && n[i] <= '9'))
{
x++;
}
else break;
i++;
}
产生4
,第二个回路将n1
设置为0
。
如果要使用循环,则程序可以按以下方式编写
#include <iostream>
#include <string>
int main()
{
std::cout << "Hello n world!" << std::endl;
std::string s;
std::cin >> s; //The number itself
unsigned int digits = 0, evens = 0;
for ( std::string::size_type i = 0; i < s.size() && s[i] >= '0' && s[i] <= '9'; i++ )
{
++digits;
evens += ( s[i] - '0' ) % 2 == 0;
}
std::cout << "The number has " << digits << " digit(s)." << std::endl;
std::cout << "The number has " << evens << " even digit(s)." << std::endl;
return 0;
}
程序输出可能看起来像
Hello n world!
1022A
The number has 4 digit(s).
The number has 3 even digit(s).
或者您可以检查字符串是否没有有效的数字表示,在这种情况下会发出错误。