gpt4 book ai didi

c++ - 码 block 循环移位

转载 作者:行者123 更新时间:2023-11-28 05:48:17 25 4
gpt4 key购买 nike

我是 C 编程的新手,一直在尝试执行这个程序来移动数字。前任。我想让4567右循环移位就变成7456。

#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
int num;
scanf("%d",&num);
int temp=num;
int flag=0;

while(temp!=0)
{
temp=temp/10;
flag++;
}
int r=num%10;
int s=num/10;
int k=pow(r,flag);
int crs=k+s;
printf("%d",crs);
return 0;
}

最佳答案

您做错的是对最右边数字(原始数字)的处理。您不想利用 flag 的力量。您想要对 10flag 的幂,并将它与最低有效(最右边)的数字相乘。

在计算数字和确定应该将最低有效数字移动多少步时,您也应该小心。例如,如果你有 123 你有三位数字,但你应该只将最低有效数字向左移动两步(其余的向右移动一步)。当数字为 0 时,可能会特别考虑 - 无论如何你都会得到零,这可能是你想要的。您还应该考虑如何处理负数。

类似于:

#include<stdio.h>

#include<math.h>

using namespace std;
int main()
{
int num;
scanf("%d",&num);
int temp=num;
int flag=0;

while(temp!=0)
{
temp=temp/10;
flag++;
}
int r=num%10;
int s=num/10;
int k=r*pow(10,flag-1); // <- here's the fix
int crs=k+s;

printf("%d",crs);

return 0;
}

当然还有一些细节。如果您正在编写 C++,则不应包含 stdio.hmath.h。相反,您应该包括 cstdiocmath(有些人可能会提示使用 cstdio 并说您应该改用 iostreams,但这只是一个意见问题)。

关于c++ - 码 block 循环移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790454/

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