-1

//this code is accepting only the first input from the user even if there are multiple test cases provided.

    #include <bits/stdc++.h>
    using namespace std;
    int main()
    { 
      int t,n,ans,a, b, d, c, i,j; 
      cin>>t;
      while(t>0)
      { 
       c=0;
       cin>>n; 
       d = n;
       while(n!=0)
       {
         a = n; n=n/10; b = a % 10;
         if (d % b == 0)  c++; 
         else continue; 
       }
       cout<<c<<"\n";
       t--; 
      }
      return 0;
    }
PGreen_xyz
  • 71
  • 1
  • 1
  • 7
  • Aside from the ghastly code "style", you're using `std::cin` only once outside of any loop. – Quentin Feb 19 '19 at 13:02
  • The code works well (i.e accepts multiple inputs) after removing inner or second while loop. So can you please elaborate? Also, your suggestion to improve the code style will be of great help. @Quentin – PGreen_xyz Feb 19 '19 at 13:18
  • That's because I'm sleep-deprived and didn't see the `cin>>n;` line, my bad. About code style: ditch [``](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), indent and space your code consistently to make it more readable, use descriptive variable names, declare variables in the smallest scope possible. – Quentin Feb 19 '19 at 13:25
  • @Quentin Yes I will keep the points in mind. So now, that you saw the `cin>>n;` line, please tell the mistake. Thanks. – PGreen_xyz Feb 19 '19 at 13:45
  • I actually can't reproduce your issue. What input are you using? Note that your algorithm does not work for numbers with zeroes such as `10`, it will trigger UB. – Quentin Feb 20 '19 at 10:07
  • @Quentin Exactly. I checked its not working only for inputs with '0'. What is the reason for this? – PGreen_xyz Feb 20 '19 at 12:14
  • Because `d % b` when `b` is zero is undefined behaviour. You need to check for that case and react accordingly. By the way, [here](https://wandbox.org/permlink/vWw2pb2R8BHVsgit) is a refactored version of your code to match what one would expect a C++ version to look like. The fix is on lines 24-25. – Quentin Feb 20 '19 at 12:17
  • @Quentin Yeah. I just added `if(b==0) continue;`, it worked. Thanks a lot. – PGreen_xyz Feb 20 '19 at 15:07

1 Answers1

0

Replace while(t>0) with while(t--) and remove the t--; in the same while loop

Mann
  • 89
  • 1
  • 7