计算输入数字的次数,直到输入第一个对称数字
Count how many times number entered until the first symmetry number is entered
我编写了以下代码,但仅在第一个数字对称时才有效:
对称性就像这个数字:4554(从两端读取是相同的数字)
我的问题是为什么中断仅适用于第一个数字?当我运行它时,它就会发生。
#include <iostream>
using namespace std;
int main()
{
int n=0, z=0, r=0, x=0, m;
for (;;) {
cout << "Enter number: ";
cin >> x;
m = x;
while(x!=0) {
r = x % 10;
z = z * 10 + r;
x = x / 10;
}
if(m==z)
break;
else
n++;
}
cout << n;
return 0;
}
Move int z=0, r=0; inside for loop。
为什么不使用这段代码来知道数字是否对称?
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int x;
for (;;) {
cout << "Enter number: ";
cin >> x;
m = x;
std::stringstream str;
str << x;
std::string number = str.str();
if ( number == std::string( number.rbegin(), number.rend() )
break;
else
n++;
}
cout << n;
return 0;
}
更简单,导致相同的结果,并且肯定更容易出错;-)
如果你这样写,推理会容易得多:
#include <iostream>
bool isPalindrome(int x)
{
int y = x;
int z;
while (x) {
z = z * 10 + x % 10;
x /= 10;
}
return y == z;
}
int main()
{
int n = 0;
int x;
for (;;) {
std::cout << "Enter number: ";
std::cin >> x;
if (isPalindrome(x))
break;
else
++n;
}
std::out << "Number of non-palindromes: " << n << std::endl;
return 0;
}
具有有意义名称的函数总是有帮助的!
相关文章:
- 如果输入数字为负数,如何循环
- C++程序来查找输入数字的最小/最大值
- 如何接受可变的输入数字?
- cin.fail 在输入数字和字母时不起作用
- 如何在函数中输入数字以输出单词?
- 如果用户输入数字 <0,我如何停止" while loop "?
- C++:如果用户输入数字将其转换为单词,并且如果按回车键程序应退出,则使用开关大小写
- 如何使用正则表达式将输入数字格式化为字符串
- 当我运行我的程序时,即使"user"输入数字||C++ 绘画作业
- C 如何进行计数循环,该循环确定两个输入数字中的哪个是最低的,并且从那里计数
- 如何要求用户在类函数中输入数字
- 输入数字输入到if语句中
- 为什么 cin.fail() 在输入数字后跟字符时不返回 false?
- search用字符串列表输入数字(类似于t9字典)
- 试图创建一个函数来查找用户输入数字的斐波那契数
- 如何允许用户输入数字和运算符
- QTreeWidgetItem 可编辑仅允许输入数字
- 如何提示用户输入数字,直到他们选择奇数?C++
- 输入数字,直到输入 -1
- 编写一个程序,输入数字 1-12 并输出相应的月份