Task:

enter image description here


Here is the code, I can not find the error. Everything works, but when I send it to check it gives an error.

#include <iostream> #include <math.h> here using namespace std; struct arrayInfo { int mas1; int mas2; }; int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int size; cin>>size; int sum=0; int s=0; int k=1; arrayInfo *arr =new arrayInfo[size]; for(int i=0;i<size;i++) { cin>>arr[i].mas1; } for(int i=0;i<size;i++) { while((arr[i].mas1/k)%10!=0) { s=(arr[i].mas1/k)%10; sum=sum+s; k=k*10; } arr[i].mas2=abs(sum); k=1; sum=0; } for(int i=0;i<size-1;i++) for(int i=0;i<size-1;i++) { if(arr[i].mas2>arr[i+1].mas2) { arrayInfo temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } for(int j=0;j<size-1;j++) for(int i=0;i<size-1;i++) { if(arr[i].mas2==arr[i+1].mas2) if(arr[i].mas1>arr[i+1].mas1) { int t=arr[i].mas1; arr[i].mas1=arr[i+1].mas1; arr[i+1].mas1=t; } } for(int i=0;i<size;i++) cout<<arr[i].mas1<<" "; } 
  • one
    The code does not take into account that there may be 0 in the middle of the number. In general, I recommend the standard sorting functions and rewrite the calculation of the sum of digits into a separate function. - pavel
  • @pavel but who will use the standard functions in the training task . - αλεχολυτ
  • one
    @pavel "pour water out of the kettle, than reduce the task to the previous one" :) - Nick Volynkin

2 answers 2

As far as C ++ is concerned, it is better to implement it in terms of C ++, and not C. The code is clear, flexible and understandable.

 #include <iostream> #include <vector> class specialLess { public: bool operator()(int rhs, int lhs) const { unsigned rhsSum = specialSum(rhs); unsigned lhsSum = specialSum(lhs); if(rhsSum != lhsSum) { return rhsSum < lhsSum; } return rhs < lhs; } private: unsigned specialSum(int val) const { unsigned result(0); val = abs(val); while(val >= 1) { result += val % 10; val /= 10; } return result; } }; int main(int argc, char* argv[]) { //std::vector<int> numbers{123, -129, 211}; std::vector<int> numbers{21, 3, 81, 27}; std::sort(numbers.begin(), numbers.end(), specialLess()); for(int item : numbers) { std::cout << item << " "; } std::cout << std::endl; } 

    If you can include:

     #include <fstream> #include <vector> #include <iterator> using namespace std; int sum(int n) { n = abs(n); int sum = 0; while(n) { sum += n % 10; n /= 10; } return sum; } bool s(int x,int y) { int s1 = sum(x); int s2 = sum(y); return (s1 < s1) || (s1 == s2 && x<y); } int main() { vector<int> vec; ifstream fin("input.txt"); ofstream fout("output.txt"); int size; fin >> size; // он нам не нужен:D copy(istream_iterator<int>(fin), istream_iterator<int>(), back_inserter(vec)); sort(vec.begin(), vec.end(), s); copy(vec.begin(), vec.end(), ostream_iterator<int>(fout," ")); } 

    Ps. if you can't use any functions, I can tweak a little.