反向输出一个三位数C + +编程0在第一位时不能输出0,请教我一下
可以从输入获取一个三位数,然后提取其个十百位,各位数字分别乘以100,10,1后转为反向后的数,再打印即可,原数的第一位个位如果为0,乘以100,各位相加后,反向的数就不会显示百位的0了。
代码如下:
#include <iostream>
using namespace std;
int main(void){
int num;
cout<<"请输入一个三位数:";
cin>>num; // 从输入获取一个整数
// 判断输入的数是否为三位数,如果不是,则再次读取一个整数,直到读取到一个三位数
while(num<100||num>999){
cout<<"请输入一个三位数:";
cin>>num; // 从输入获取一个整数
}
int one = num%10; // 提取个位
int ten = num/10%10; // 提取十位
int hundred = num/100%10; // 提取百位
// 将个十百位,反向乘以对应的权值,转为反向后的数
// 这里原数的个位如果为0,乘以100,各位相加后,就不会显示开头的0了
int result = one*100 +ten*10 +hundred;
cout<<"反向后为:"<< result;
return 0;
}
转自百度定义:拷贝构造函数,又称复制构造函数,是一种特殊的构造函数,它由编译器调用来完成一些基于同一类的其他对象的构建及初始化。其形参必须是引用,但并不限制为const,一般普遍的会加上const限制。此函数经常用在函数调用时用户定义类型的值传递及返回。拷贝构造函数要调用基类的拷贝构造函数和成员函数。如果可以的话,它将用常量方式调用,另外,也可以用非常量方式调用。
对于普通类型的对象来说,它们之间的复制是很简单的,例如:
int a = 100;
int b = a;
而类对象与普通对象不同,类对象内部结构一般较为复杂,存在各种成员变量。
下面看一个类对象拷贝的简单例子。
#include<iostream>
using namespace std;
class CExample
{
private:
int a;
public:
//构造函数
CExample(int b)
{
a=b;
printf("constructor is called\n");
}
//拷贝构造函数
CExample(const CExample & c)
{
a=c.a;
printf("copy constructor is called\n");
}
//析构函数
~CExample()
{
cout<<"destructor is called\n";
}
void Show()
{
cout<<a<<endl;
}
};
int main()
{
CExample A(100);
CExample B=A;
B.Show();
return 0;
}
程序运行结果如下:
constructor is called
copy constructor is called
100
destructor is called
destructor is called
运行程序,屏幕输出100。从以上代码的运行结果可以看出,系统为对象 B 分配了内存并完成了与对象 A 的复制过程。就类对象而言,相同类型的类对象是通过拷贝构造函数来完成整个复制过程的。
CExample(const CExample& C) 就是我们自定义的拷贝构造函数。可见,拷贝构造函数是一种特殊的构造函数,函数的名称必须和类名称一致,它必须的一个参数是本类型的一个引用变量。
解决方案:
根据问题描述,我们需要将一个三位数反向输出,但当第一位为0时不输出0。我们可以将该三位数转换为字符串,然后对字符串进行反向操作。具体步骤如下:
#include <string>
#include <iostream>
std::string numToStr(int num) {
std::string numStr = std::to_string(num);
return numStr;
}
void reverseString(std::string& str) {
int low = 0;
int high = str.length() - 1;
while (low < high) {
std::swap(str[low], str[high]);
low++;
high--;
}
}
void removeLeadingZero(std::string& str) {
if (str[0] == '0') {
str.erase(str.begin());
}
}
int main() {
int num = 405;
std::string numStr = numToStr(num);
reverseString(numStr);
removeLeadingZero(numStr);
std::cout << numStr << std::endl;
return 0;
}
将以上代码放在一起,可以得到如下格式的markdown代码:
```cpp
#include <string>
#include <iostream>
std::string numToStr(int num) {
std::string numStr = std::to_string(num);
return numStr;
}
void reverseString(std::string& str) {
int low = 0;
int high = str.length() - 1;
while (low < high) {
std::swap(str[low], str[high]);
low++;
high--;
}
}
void removeLeadingZero(std::string& str) {
if (str[0] == '0') {
str.erase(str.begin());
}
}
int main() {
int num = 405;
std::string numStr = numToStr(num);
reverseString(numStr);
removeLeadingZero(numStr);
std::cout << numStr << std::endl;
return 0;
}