大佬帮忙看看为啥编译失败

P1307 [NOIP2011 普及组] 数字反转

7teen @ 2022-11-28 22:25:52


#include <bits/stdc++.h>
using namespace std;
int n, a[10000];
int index = 1,ans = 0;
int main()
{

    cin >> n;
    ans = n;
    if(n < 0){
        n = abs(n);
    }

    while(n){
        a[index] =  n % 10;
        n /= 10;
        index++;
    }
    if(ans < 0){
        cout << "-";    
    }

    for(int i = 1;i <= index;i++){
        if(a[i] == 0){
            a[i] = a[i+1];
        }
    }

    for(int i = 1;i < index;i++){
        cout << a[i];
    }
    return 0;
}

by ud2_ @ 2022-11-28 22:31:50

如果一定要用全局变量,那么放进 namespace

@@ -1,9 +1,10 @@

 #include <bits/stdc++.h>
 using namespace std;
+namespace {
 int n, a[10000];
 int index = 1,ans = 0;
-int main()
+void my_main()
 {

     cin >> n;
@@ -30,5 +31,7 @@
     for(int i = 1;i < index;i++){
         cout << a[i];
     }
-    return 0;
 }
+}
+
+int main() { my_main(); }

by jnyz2021109122116 @ 2022-11-28 22:31:55

@7teen index是函数名,和命名空间冲突了


by Lunar_Hjj @ 2022-11-28 22:32:25

应该是变量名index的问题,改了一下就过了

#include <bits/stdc++.h>
using namespace std;
int n, a[10000];
int ind = 1,ans = 0;
int main()
{

    cin >> n;
    ans = n;
    if(n < 0){
        n = abs(n);
    }

    while(n){
        a[ind] =  n % 10;
        n /= 10;
        ind++;
    }
    if(ans < 0){
        cout << "-";    
    }

    for(int i = 1;i <= ind;i++){
        if(a[i] == 0){
            a[i] = a[i+1];
        }
    }

    for(int i = 1;i < ind;i++){
        cout << a[i];
    }
    return 0;
}

|