繁体   English   中英

如何交换 c++ 中数字的第一位和最后一位

[英]How to swap first and last digit in number in c++

我不明白为什么下面的代码总是用0回答。

#include <iostream>
using namespace std;

int main() {

    int n,a,b;
    cin>>n;
    b=n%10;

    while(n!=0) {
        a=n%10;
        n=n/10;     
    }
    a=b;
    b=a;
    cout<<n<<endl;
    return 0;
}

要交换两个号码,您需要一个临时寄存器

tmp=a;
a=b;
b=tmp;

但是,如果要交换n数字,则需要更改n 您在循环中已销毁的对象。 事先保留一份副本?

或者简单地注意一下floor(log(n)/log(10))给您的第一个数字为10的幂。

n=23456;
int firstdec = pow(10,floor(log(n)/log(10))); // eg 10000
int firstdig = n/firstdec; // eg 2
int lastdig  = n%10; // eg 6
int removed  = ((n-firstdig*firstdec)/10)*10 ; // eg 3450
int final    = removed + lastdig*firstdec + firstdig; // eg 63452

这个

a=b;
b=a;

看起来不错。 你是说swap(a, b)还是

int t = a;
a = b;
b = t;

而且您实际上并没有更改n

#include <iostream>
#include<math.h>

using namespace std;

int main()
{
    int num, swno;
    int fd, ld, digits;

    // Reads a number from user
    cout<<"Enter any number:";
    cin>>num;

    ld = num % 10; //Gets last digit
    digits = (int)log10(num); //Total number of digits - 1
    fd = (int)(num / pow(10, digits)); //Gets the first digit

    swno = ld;
    swno *= (int)pow(10, digits);
    swno += num % ((int)pow(10, digits));
    swno -= ld;
    swno += fd;

    cout<<"\nOriginal number = "<<num;
    cout<<"\nNumber after swapping first and last digit: "<<swno;

    return 0;
}

您的代码有一些问题,例如变量交换。 但是,您似乎也希望通过更改ab来相应地更改n ,这不会发生。

首先,因为ab不是数字的引用,所以它们仅仅是副本。 其次,你摧毁了你nloop发现a ,所以即使您解决您交换代码仍然会打印0

我的建议是将整数转换为字符串,更改第一个和最后一个,然后将其转换回。 这将更加简单和可读。

为此,您应该看一下stringstream

#include <iostream>
#include<string.h>

using namespace std;

int main(void){
    
    int a;
    char k,l;
    cin>>a;
    string s=to_string(a);
    k=s[0];
    l=s[s.length()-1];
    s[0]=l;
    s[s.length()-1]=k;
    cout<<s;
    
    return 0;
}

这是您的代码中缺少的内容。 实数=输入的值,第一个和最后一个数字=首个和最后一个,i =输入的数字的位数。

real -= lastd;
    real += firstd;
    real -= (firstd*i);
    real += (lastd*i);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM