Show number of numerators = 3 in a struct

2

I have the following program in C the user enters numerators and denominators in an integer struct and the number of numerators with value "3" must be displayed:

 #include <iostream>
 #include <stdio.h>
 #include <stdlib.h>

 using namespace std;

 //Se declara un array de tipo struct

 typedef struct fraccion

 {

  int numerador, denominador;

 }fraccion;

 //fin de declaracion de tipo struct llamado "fraccion" y con variables 
 "numerador y denominador"


  int main()
  {
   //Array de 3 fracciones

  fraccion arrFraccion[3];

   int i = 0;
   int Contador=0;

   int num = 1;

   while (num == 1)

   {

   int seleccion; //declara una variable de tipo entera llamada "seleccion"               para el menu mas abajo

   printf("\nPresione 1 para ingresar una fraccion\n"); //opcion 1 del menu para igresar una fraccion
   scanf("%d", &seleccion); //Se ingresa el valor

if(seleccion == 1)

 {  //Inicio del if

for (i=0; i<3; i++)
    {
        printf("\nIngrese su fraccion, numerador seguido de denominador\n");
        scanf("%d %d",&arrFraccion[i].numerador, &arrFraccion[i].denominador);//Usuario ingresa valores

      if (&arrFraccion.numerador==3) //si el valor de numerador es = a 3
        {
                Contador ++; //incrementa el contador

         } //fin del if del contador

       i++; //Incrementa el indice
       }
       printf ("La cantidad de numeradores con el numero 3 son: ", Contador);
   }
return 0;
 }
}

My question is: why do not you show me the number of numerators with the number 3?

Only unfolds empty:

Greetings and thank you very much!

    
asked by FLL 10.07.2018 в 08:11
source

1 answer

3

Your problem is this:

if (&arrFraccion.numerador==3) //si el valor de numerador es = a 3

That line does not check if the value of the numerator is three; check if the memory address of the element numerador of the instance arrFraccion is three; which will never be true.

Furthermore, that instruction does not compile either since arrFraccion is a formation 1 , the name of the formation is equivalent to a pointer to the first element, therefore you could not use the dot operator ( . ) to access the numerador element: you should use the arrow operator ( -> ).

This would be a possible version of your corrected code:

if (&arrFraccion[i].numerador==3) //si el valor de numerador es = a 3

Notice that I have not used the arrow; this is because I am not using the name of the formation but I am indexing it with the operator brackets ( [] ) that returns an instance, not a pointer.

  • Also known as an array, or in English: array.
  • answered by 10.07.2018 в 08:20