0

I have a program in C language about checking a number in an array which is symmetric or not. In some cases such as 123.321 or 100.001, do program works well. However, 10.01 is not the expected output. Please help me to find out the problem!

Also, maybe the idea in this program is not good, can you suggest other solutions? Thank you very much!

Here is my code.

#include <stdio.h>

int main(){
    int n;
    scanf("%d",&n); // numbers of elements in array
    float a[100];
    int i;
    for(i=0;i<n;i++){
        scanf("%f",&a[i]);
    }
    for(i=0;i<n;i++){
        float r;
        int c,k;
        r=a[i];

        // checking if the number is decimal or not
        if (r==(int)a[i]){
        }else{
            while (r!=(int) r){
                r=r*10;
            }            
        }
        c=(int)r;
        k=c;

        // checking if the number is symmetric or not
        int nReverse = 0, nRemain;

        while (c != 0)
        {
            nRemain = c % 10;   
            nReverse = (nReverse * 10) + nRemain;
            c = c / 10;
        }

        if(nReverse!=k){
            printf("\n%f is not symmetric ",a[i]);
        }else{
            printf("\n%f is symmetric",a[i]);
        }
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Welcome to SO. You seem to assume that a `float` can hold any number. This is not true. The precision and accuracy of floating point data types is limited. Some numbers like `0.1` cannot be stored correctly. You can improve the situation by using `double` instead of `float` but you should read about limitations of floating point math. – Gerhardh Jul 02 '21 at 15:45
  • 1
    Values stored in the computer as floats do not have digits. They are in binary form. Compare strings instead. – stark Jul 02 '21 at 15:45
  • @Gerhardh That's an accuracy problem, not precision. – Barmar Jul 02 '21 at 15:46
  • 2
    For this problem I suggest you stay in string format. – 500 - Internal Server Error Jul 02 '21 at 15:47
  • @Barmar true. in the end both are limited. – Gerhardh Jul 02 '21 at 15:47

0 Answers0