1
#include<iostream>
#include<cmath>
using namespace std;
int main(){
    int n,l=0,a,s,d,w;
    cin>>n;
    a=n;
    while(a!=0){
        l++;
        a=a/10;
    }
    if(l%2==0){
        s=n/pow(10,(l/2)+1);
        w=pow(10,(l/2)-1);
        d=n%w;
        } else{
        s=n/pow(10,l/2+1);
        w=pow(10,l/2);
        d=n%w;
    }
    cout<<s*(pow(10,(l/2)-1));
}

When I input "12345" it should show "1245", but instead it shows "120". Why does it? The code should eliminate the middle digit for uneven numbers, or two middle digits for even numbers, but the right side of the number (variable d) doesn't show the right thing.

alexb
  • 13
  • 2

3 Answers3

0

d is not part of the output. so it's calculation will not be shown.

if(l%2==0){
    s=n/pow(10,(l/2)+1);
    w=pow(10,(l/2)-1);
    d=n%w;
    } else{
    s=n/pow(10,l/2+1);
    w=pow(10,l/2);
    d=n%w;
    // if n == 12345, I get
    // s = 12
    // w = 100
    // d = 45
    // l = 5
}
cout<<s*(pow(10,(l/2)-1));
// outputs 120 (s * 10^ 1) == s * 10

I can see d not used, but what further is unexpected

mksteve
  • 12,614
  • 3
  • 28
  • 50
0

You didn't add d part to your last calculation:
l should be modified for even and odd differently.

Try:

if(l%2==0){
    s=n/pow(10,(l/2)+1);
    w=pow(10,(l/2)-1);
    d=n%w;
    l = l/2 - 1;
} else{
    s=n/pow(10,(l/2) + 1); 
    w=pow(10,l/2); 
    d=n%w; 
    l = l/2;
}
cout<<s * pow(10, l) + d<<std::endl;
Praveen
  • 8,945
  • 4
  • 31
  • 49
  • Did you try with the given code (`from if to last`) ?? I am getting 1245 for 12345. – Praveen Dec 05 '15 at 08:27
  • I did try with this: `#include #include using namespace std; int main(){ int n,l=0,a,s,d,w; cin>>n; a=n; while(a!=0){ l++; a=a/10; } if(l%2==0){ s=n/pow(10,(l/2)+1); w=pow(10,(l/2)-1); d=n%w; l = l/2 - 1; } else{ s=n/pow(10,(l/2) + 1); w=pow(10,l/2); d=n%w; l = l/2; } cout< – alexb Dec 05 '15 at 08:30
  • The code did work for me. May be you need to compile it before test!! – Praveen Dec 05 '15 at 08:34
0

Here's working code

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int n,l=0,a,s,d,w, result;
    cin>>n;
    a=n;
    while(a!=0)
    {
        l++;
        a=a/10;
    }
    if(l%2==0)
    {
        s=n/ceil(pow(10,(l/2)+1));
        w=ceil(pow(10,(l/2)-1));
        d=n%w;
        result = s*(ceil(pow(10,(l/2-1))))+d;
    }
    else
    {
        s=n/ceil(pow(10,l/2+1));
        w=ceil(pow(10,l/2));
        d=n%w;
        result = s*(ceil(pow(10,(l/2))))+d;
    }
    cout<<result<<endl;
}

ceil used to handle double precision problem with pow.

Community
  • 1
  • 1
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42