Where is the mistake?

#include <iostream> #include <math.h> using namespace std; int main() { int n, a, otv = 0; cin >> n; int arr[n]; for(int i = 0; i < n; i++) cin >> arr[i]; for(int i = 0; i < n; i++) { a = arr[i]; if( sqrt(a) == 0 ) otv++; } cout << otv; system("PAUSE"); return EXIT_SUCCESS; } 

The answer is 0 = /

  • one
    well, if "a == 0", then otv will not be 0: \ honestly quite incomprehensible construction, are you looking for zeros in the array in this way? so why sqrt? or something I do not understand? What do you want to get? - lirik90
  • @ lirik90 no, my task is to find in the array numbers that have roots. Therefore, I want to right now extract the root, and if the root of the number = 0, then the answer is correct and the answer is ++. But he brings me 0 - navi1893
  • Excuse me, but what root number except 0 will be 0? - lirik90
  • @ lirik90 updated code. Laid out all. See - navi1893

1 answer 1

Maybe something like this is necessary ???

 #include <iostream> #include <math.h> using namespace std; int main() { int n, a, otv = 0; double b; cin >> n; int* arr = new int[n]; for(int i = 0; i < n; i++) cin >> arr[i]; for(int i = 0; i < n; i++) { a = arr[i]; b = sqrt(a); if (b - int(b) == 0.0) otv++; } delete[] arr; cout << otv; system("PAUSE"); } 
  • for double == use is bad. Correct fabs (b - int (b)) <EPSILON - Yura Ivanov
  • @Yura Ivanov, it sounds bad !!! Can you give an example when it will not work correctly ?! - lirik90
  • @ lirik90, one double number is almost guaranteed not to be exactly equal to another double, unless of course it is the same number or if the numbers are not obtained in the process of the same calculations. - insolor