c++ - 如何在将它乘以数字时保持结尾为0

How to keep the end 0 when multiply it by a number in c++

我有这样的程序

   cin >> input;
   input *= x (a random number just dont care)
   cout << input;

一切正常,直到输入数字为 00 然后打印 0

你怎么能保留另一个号码 0 呢?提前致谢。

我不明白你的问题...0、00、000 是相同的数字,但在 C++ 中,以 0 开头的数字表示基数是八进制而不是十进制...确实 int a = 08不会编译。另请注意,以 0x 开头的数字表示十六进制,并且从 C++20 开始,以 0b 开头的数字是二进制的。

如果你想用某种格式打印数字,你主要有两种不同的方法:使用流和 C++20 格式库。

是格式化输出的“旧”方式:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  cout << setw(2) << setfill('0') << 0 << endl; // this will output 00
  cout << setw(2) << setfill('a') << 0 << endl; // this will output a0
  return 0;
}
  • setw:设置字段宽度
  • setfill:设置字符填充字段

setw仅对下一个字段有效,而setfill永久更改流!

更多信息可以看https://en.cppreference.com/w/cpp/header/iomanip

{fmt}

C++20 引入了 python-like 格式化 api

#include <iostream>
#include <format>
using namespace std;

int main() {
  cout << format("{0:2}") << endl;
  return 0;
}

更多信息可以看https://en.cppreference.com/w/cpp/utility/format/format and https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification