gpt4 book ai didi

c - 在 C 中将整数的最后两位作为字符串返回

转载 作者:行者123 更新时间:2023-12-02 05:47:18 25 4
gpt4 key购买 nike

我有一个 3 位整数myInt:

int myInt = 809;

我需要一个输出字符串 *myStr,它由最后 2 位数字组成。因此

char *mystr = "09";

最简单的解决方案是什么?

最佳答案

你可以这样做:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
char buf[32];
int myInt = 809;
char* mystr;
snprintf(buf, sizeof buf, "%d", myInt);
if (strlen(buf) > 2)
mystr = buf + strlen(buf) - 2;
else
mystr = buf;
fputs(mystr, stdout);
return 0;
}

关于c - 在 C 中将整数的最后两位作为字符串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53185370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com