samedi 13 novembre 2021

c language error when using comma as separator for multiple number inputs

I have this program where it lets the user input a list of numbers, then the program finds the largest number amongst the inputs, and count how many times that largest number was inputted.

When I use space as a separator, the program runs well. But when I use a comma as a separator, there seems to be a logical error.

Here is my source code:

int i, numberOfIntegers, listOfIntegers, largest = 0, occurrence = 0;

printf("\n \t \t \t Finding the LARGEST integer \n");

printf("\n How many integers do you want to enter? ");
scanf("%i", &numberOfIntegers);

printf("\n Input %i list of integers: \n ", numberOfIntegers);

for (i = 1; i <= numberOfIntegers; i++)
{
    printf("\t");
    scanf("%i", &listOfIntegers);

    if (listOfIntegers > largest)
    {
        largest = listOfIntegers;
        occurrence = 1;
    }
    else if (listOfIntegers == largest)
    {
        occurrence++;
    }
}

printf("\n The largest value is %i and the number of occurrence is %i \n ", largest, occurrence);

return 0;

Here is an example of output where I use a comma as a separator:

How many integers do you want to enter? 4

Input 4 list of integers:
        5, 6, 6, 6

 The largest value is 5 and the number of occurrence is 4

Whereas, the correct output should be:

How many integers do you want to enter? 4

Input 4 list of integers:
        5, 6, 6, 6

 The largest value is 6 and the number of occurrence is 3

Can someone point out where exactly am I doing it wrong?

Aucun commentaire:

Enregistrer un commentaire