Temperatures: This should work, but

I am troubleshooting the following code for the Puzzle “Temperatures” related to finding temperatures closest to zero. Programming in C, I have tested it dozens of times on three different IDEs (Code::Blocks, Dev-C++, and CLion), all of which work perfectly. However, when I run in the CodinGame IDE, it produces an error. Specifically, it sends the value 1 to stdout instead of the expected correct value closest to zero. The strategy I used was to place the scanf() temperatures into an array of size n, order them by the absolute value (abs()) of the number, and printf() the value in the first index of the ordered array. Some simple program control at the end deals with the case of selecting positive over negative values when their absolute values are equal (e.g., if selecting between -5 and 5, choose 5). Does CodinGame not accept arrays or pointers?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// User defined function prototype
void swap(int *xp, int *yp);

int main()
{
    int n; // the number of temperatures to analyse
    int temp[n]; // Declare an array of size n
    scanf("%d", &n); // System reads size
    for (int i = 0; i < n; i++) 
    {
        int t;
        temp[i] = scanf("%d", &t); //<-- inputs scanf() into an array
    }

    int j, i, min_idx;

    for ( i = 0; i < n-1; i++ )
    {
        min_idx = i;
        for ( j = i+1; j < n; j++ )
        {
            if ( abs(temp[j]) < abs(temp[min_idx]) )
            {
                min_idx = j;
            }
        }
        // User defined function to swap array elements
        swap(&temp[min_idx], &temp[i]); 
    }
    // Program control to deal with 5 or -5
    if ( abs(temp[0]) == abs(temp[1]) && temp[1] > temp[0] )
    {
        printf("%d\n", temp[1]);
    }
    else
        printf("%d\n", temp[0]);
    
    return 0;
}

/*swap() -- user defined function that swaps values from an array. */
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
temp[i] = scanf("%d", &t); 

scanf returns the number of items scanned, so you just fill your array with 1’s.

2 Likes

@RoboStac, thanks for your reply! So how does the coder access the values? The way the comments were written in the CodinGame, it reads as if n is the number of items scanned, and t are supposed to be the values returned.

scanf("%d", &temp[i]);
2 Likes

@Niako, thank you very much! That was the solved issue. 100% passed all the tests.