如何截掉前导数字? C++

发布于 2024-09-24 13:36:31 字数 218 浏览 0 评论 0原文

如何截掉数字的前导数字,以便仅显示最后两位数字,而不使用库。例如:

1923 至 23

2001 至 01

1234 至 34

123 至 23

仅​​包含

#include <iomanip>
#include <iostream>

感谢!

How can I cut off the leading digits of a number in order to only display the last two digits, without using the library. For example:

1923 to 23

2001 to 01

1234 to 34

123 to 23

with only

#include <iomanip>
#include <iostream>

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乞讨 2024-10-01 13:36:31

如果您只是使用整数,为了简单起见,我建议只执行 mod %100:

int num =2341;

cout << num%100;

将显示 41。

如果您需要前导零,只需执行以下操作:

std::cout << std::setw(2) << std::setfill('0') << num%100 << std::endl;

If you're just working with integers I'd suggest just doing mod %100 for simplicity:

int num =2341;

cout << num%100;

Would display 41.

And if you need a leading zero just do:

std::cout << std::setw(2) << std::setfill('0') << num%100 << std::endl;
娇女薄笑 2024-10-01 13:36:31

如果您的数字是 int 形式(而不是字符串形式),您应该考虑使用 取模运算符。

如果数字采用 char[] 形式,则有一个简单的解决方案,涉及对字符串进行索引,例如:

char *myString = "ABCDE";
int lengthOfMyString = 5;
cout << myString[lengthOfMyString - 3]
     << myString[lengthOfMyString - 5]
     << myString[lengthOfMyString - 4];
//outputs the word CAB

If your numbers are in int form (rather than string form), you should think about using the modulo operator.

If the numbers are in char[] form, there is an easy solution that involves indexing into the string, like:

char *myString = "ABCDE";
int lengthOfMyString = 5;
cout << myString[lengthOfMyString - 3]
     << myString[lengthOfMyString - 5]
     << myString[lengthOfMyString - 4];
//outputs the word CAB
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文