Problem with functions

I have a problem. This is a source code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cmath>

using namespace std;

int znam(int a){
    int br;
    do{
      a/=10;
      br++;
    }while(a);
    return br;
}

int pre(int a){
    int uk=0;
    for(int x=0;x<a;x++){
        uk+=((x+1)*9*pow(10,x));
    }
    return uk;
}

int main()
{
    int n;
    cin>>n;
    int zn=znam(n);
    int br=(n-pow(10,(znam(n)-1))+1);
    cout<<br<<endl;
    return 0;
}


When it is written like this, program backs me some unknown and unlogical result. But when I remove:
int zn=znam(n);
it shows me right result. I don't know why is this happening. Please help!
1
2
3
4
5
6
7
8
int znam(int a){
    int br;
    do{
      a/=10;
      br++;
    }while(a);
    return br;
}


In this function, your first use of br is br++, which means add 1 to the current value of br, but you haven't initialized br, so its current value is undefined. Consider initializing the variable br in this function before using it.
Last edited on
I bet your problem is because br is not initialized (make it int br = 0;)
Though what is it that this code calculates?
br is not initialized, it can be anything at line 7. It's only luck that it appears to be working on the first call to the function because the memory allocated for br happens to be zero (and by the next call, it sounds like it is given memory that has a random value in it already).
Thanks for help! Problem solved!
Topic archived. No new replies allowed.