Help with While in c++

Asked

Viewed 54 times

2

I was curious about the following code in c++.

int main(int argc, char** argv) {
    float n1,n2,n3,n4;
    int i = 1;
    char nomeAluno;
    
    printf("Digite seu nome: ");
    scanf("%s", &nomeAluno);
    while(i<5){
        printf("Digite sua %dº nota: ", i);
        scanf("%f", &n1);
        
        i++;
    }
    printf("%.1f \n", n1);
    printf("%.1f \n", n2);
    printf("%.1f \n", n3);
    printf("%.1f \n", n4);
    return 0;
}

I have the following doubt, I don’t know if it’s possible, but if it’s how I can get inside the while the next note typing falls inside the N2? Because this way I did it keeps storing only in n1(Of course because of the loop).

  • 2

    The statement char nomeAluno; defines the variable that will contain one single character (in this case the format is %c) and not a string. For a string, which in C is an array of characters with the terminator character ' 0', use char nomeAluno[40]; and in the scanf function do not put &. In fact in C++ you should use the string class. As for the notes you put the reading inside a loop and therefore every new reading you overwrite what was read in the previous reading. Either take separate readings for each note or use an array of notes (float nota[4];).

  • I didn’t notice the difference between using %c and %s over & didn’t know it was better to use a string. I’ll study more anyway and I’m grateful for the advice. :)

1 answer

3

You can use vectors. To declare them, it is simple, just type the variable and then between keys [] the number of positions that will receive the variable float n[4], here I declared a float type array of 4 positions (remembering that C++ the values of a vector start with 0).

A practical example of what your code would look like:

int i = 0;
float n[4];
while(i<4){
    printf("Digite sua %dº nota: ", i+1);
    scanf("%f", &n[i]);
    
    i++;
}
printf("%.1f \n", n[0]);
printf("%.1f \n", n[1]);
printf("%.1f \n", n[2]);
printf("%.1f \n", n[3]);
return 0;
}

Note that I declare int i = 0, and that in the printf, I add i + 1 to print in the way that has to be shown to the user, this value will change only in printing, and will not add in variable i.

To see more about, I recommend these two links:

http://linguagemc.com.br/vetores-ou-arrays-em-linguagem-c/

https://www.inf.pucrs.br/~pinho/Laproi/Vectors/Vectors.htm

  • Thank you, I will use vectors then. And thank you for the links. D

  • You’re welcome, my friend, you had an errata, in while() i put while(i<5), actually is while(i<4) and read enquanto i for menor que 4, because we only have four positions to fill, and the variable i begins with 0, now that’s correct. Remembering that it is dangerous in a program to give values to a vector larger than itself, you are changing the memory that may be being used by another instance, variable, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.