进制转换 显示答案错误

进制转换 显示答案错误 但是不知道哪里错了
将十进制整数n转换成k进制数。

输入格式:
首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据输入两个整数n和k( -1000000 ≤ n ≤ 1000000, 2 ≤ k ≤ 9)。

输出格式:
对于每组测试,先输出n, 然后输出一个空格,最后输出对应的k进制数。

输入样例:
2
123 8
-12 2
输出样例:
123 173
-12 -1100

#include<iostream>
#include<stack>
using namespace std;
void traverse(int n,int &k){
    stack <int> sta;
    if(n<0) {
        n=n*(-1);
    }
    while(n>0){
        sta.push(n%k);
        n=n/k;
    }
    while(!sta.empty()){
            cout<<sta.top();
            sta.pop();
    }
}
int main(){
    int T,n,k;
    cin>>T;
    while(T--){
        cin>>n>>k;
        cout<<n<<" ";
        if(n!=0){
            traverse(n,k);
        }
        cout<<endl;
    }
}

img

修改如下,供参考:

#include<iostream>
#include<stack>
using namespace std;
void traverse(int n, int& k) {
    stack <int> sta;
    int flg = 0;
    if (n < 0) {
        n = n * (-1);
        flg = 1;
    }
    while (n > 0) {
        sta.push(n % k);
        n = n / k;
    }
    if (flg)
        cout << "-";
    while (!sta.empty()) {
        cout << sta.top();
        sta.pop();
    }
}
int main() {
    int T, n, k;
    cin >> T;
    while (T--) {
        cin >> n >> k;
        cout << n << " ";
        if (n != 0) {
            traverse(n, k);
        }
        cout << endl;
    }
}

负数转换后似乎没有加上负号