为什么这个通不过?

P1307 [NOIP2011 普及组] 数字反转

KT1001 @ 2024-04-01 15:30:37

#include<stdio.h>

int main()
{
    int n, m;
    char flag = '-';
    scanf("%d", &n);
    int t = n;
    while(t){
        int temp = t % 10;
        m = m * 10 + temp;
        t /= 10;
    }
    if(n)   printf("%d", m);
    else    printf("%c%d",flag,m);

    return 0;
}

by xxs12345 @ 2024-04-01 16:06:58

@KT1001

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,m;
    char flag='-';
    cin>>n;
    int t = n;
    while(t){
        int temp = t % 10;
        m = m * 10 + temp;
        t /= 10;
    }
    if(n)   printf("%d", m);
    else    cout<<flag<<m;
    return 0;
}

by xxs12345 @ 2024-04-01 16:07:35

@KT1001 printf的问题


by KT1001 @ 2024-04-01 16:13:34

@xxs12345 请问这个printf为什么会导致错误呢?您能解答一下吗?谢谢!


by keep_shining @ 2024-04-01 16:15:16

#include<stdio.h>

int main()
{
    int n, m=0;
    char flag = '-';
    scanf("%d", &n);
    int t = n;
    while(t){
        int temp = t % 10;
        m = m * 10 + temp;
        t /= 10;
    }
    if(n>=0)    printf("%d", m);
    else printf("%c%d",flag,-m);
    return 0;
}

by keep_shining @ 2024-04-01 16:16:31

m要赋初值0 @KT1001


by keep_shining @ 2024-04-01 16:17:22

或者放在main函数外

@KT1001


by keep_shining @ 2024-04-01 16:21:17

以后要记住


by KT1001 @ 2024-04-01 16:22:37

@QAQll955cn m赋初值或者把m放在main函数外面可以前面的测试点,但是最后一个Subtask #1却无法通过,这是怎么回事呢?


by keep_shining @ 2024-04-01 16:25:52

请你想一下n=0的情况


by keep_shining @ 2024-04-01 16:26:18

你输出-0


| 下一页