r/cpp_questions • • 1d ago

OPEN Rate my code.

I´m new at programing, I just download code::block today to start learning c++ and I got obsessed.

Here is an excersise I´ve done, and im really proud of:

#include <iostream>
using namespace std;

int precio = 80;
int desn = -30;  //desn es el descuento para niños
int desam = -35; // desam = descuento adultos mayores

int edad;

int cliente = 0;
int mayor = 0;
int menor = 0;

int recaudomenor = 50;
int recaudomayor = 45;
int recaudo = 80;

int main(){

  cout << "Bienvenido al cine. El precio del boleto regular es de $80, pero tal vez pueda obtener un descuento." << endl;

  cout << "Por favor, ingrese su edad: ";
  cin >> edad;

  while (edad != -137){

  if (edad < 12) {
  precio += desn;
  menor = menor+1;
  cout << "Felicidades, niño, tienes un descuento." << endl;
  }

  else if (edad >= 60) {
  precio += desam;
  mayor = mayor+1;
  cout << "Enhorabuena, usted tiene un descuento." << endl;
  }

  else {
  cout << "Disfrute la función, es lo único que puede." << endl;
  }

  cout << "Su total a pagar es de: $" << precio << "." << endl;

  precio = 80;
  cliente +=1;

  cout << "\n\n\n\nBienvenido al cine. El precio del boleto regular es de $80, pero tal vez pueda obtener un descuento." << endl;

  cout << "Por favor, ingrese su edad: ";
  cin >> edad;
  }

  recaudomenor = recaudomenor*menor;
  recaudomayor = recaudomayor*mayor;

  cout << "\n\nFin del día." << endl;

  cout << "Total de clientes: " << cliente << endl;

  cout << "Total de menores de edad: " << menor << endl << "Dinero recaudado: $" << recaudomenor<< endl;

  cout << "Total de mayores de edad: " << mayor << endl << "Dinero recaudado: $" << recaudomayor << endl;

  cliente = cliente-mayor-menor;
  recaudo = recaudo*cliente;

  cout << "Total de adultos: " << cliente << endl << "Dinero recaudado: $" << recaudo << endl;

  int recaudototal = recaudo+recaudomayor+recaudomenor;

  cout << "Recaudo total: $" << recaudototal;
  return 0;
}

what i do here is applying a discount to a child or an elder, taking a count of how many clients we have in a day and the money earned.

it all keeps going until i type -137 cause is my secret code. typing -137 checks the day and counts everything. its awesome.

Btw its all wrote in spanish cause im from México and i dont know if redit has spanic people, i´m also new in here.

0 Upvotes

32 comments sorted by

10

u/le_disappointment 1d ago

I would make the variables that you aren't modifying const

-3

u/Mobile_Travel_1822 1d ago

hmm, got the concern, but i don´t feel ever changing these variables anyway, ill see what i can do, thanks

4

u/wittleboi420 1d ago

I would suggest doing it from the start. When your projects get bigger, it will help!

1

u/Independent_Art_6676 21h ago

this is hard to see because you just started. In large projects, many people work on the code and it reaches large size, 10s, even 100s of thousands of lines and someone can come along and accidentally change a value thinking its a 'variable' and not a 'constant', causing a bug. If you mark it const, they try to change it, and it triggers and error which tells them not to do that. Its a great habit to get into early. So is typing std:: or smaller using statements. Using std is bad practice; its great and handy for early programs as you learn but its bad news in large projects, so you may want to stop doing that before it becomes a habit as well.

Keep at it, you are off to a great start. There are spanish language C++ resources and sites and probably forums but your english is just fine and the majority of resources for programmers will be in english so you may get better results sticking to english sites.

1

u/n1ghtyunso 6h ago

const is an extremely powerful feature of this programming language. do use it, get used to it as soon as you can.
Const lets you express your assumptions in code and the compiler will slap you when this assumption ever turns out to be wrong.
This is very helpful for overall prorgam correctness.

5

u/Kajitani-Eizan 1d ago

Not bad, a couple points for improvement:

  • Indentation (spaces or tabs at the start of the line) for each brace/code block will help to understand where braces/code blocks begin and end and what is in what scope more clearly. It should look like this:

  while (edad != -137){

    if (edad < 12) {
      precio += desn;
      menor = menor+1;
      cout << "Felicidades, niño, tienes un descuento." << endl;
    }

    else if (edad >= 60) {
      precio += desam;
      mayor = mayor+1;
      cout << "Enhorabuena, usted tiene un descuento." << endl;
    }
  • Try to minimize reuse of the same variable for a different concept. For example, recaudo starts as the ticket price, then ends as the total revenue. It should start and end as the total revenue (and start from 0).

  • Try to minimize saying the same thing twice. For example, recaudomenor should be calculated from precio, desn, and menor, instead of you needing to pre-input a value of 50, or the same welcome string should not be repeated twice in the code

There are some other points too, but you probably don't need to worry about those as a beginner. (Global variables and using namespace std)

3

u/Mobile_Travel_1822 1d ago

oh, now i know what youre talking about the indentation, its pretty good now that i can see it, it seems really useful

2

u/Mobile_Travel_1822 1d ago

i found the welcome part as a way to not fall in an endless cycle of While, and the way to count the total of clients. I used pre imputs to avoid making more complex calculations, keept it simpler, (al least for me rigth now), i might keep working on shrink the code for efficience.

the hardest part for me might be how to not fall in that while. thanks

1

u/Kajitani-Eizan 1d ago

There are some possible tricks you can do for that:

  • Set age = 0 at the start, put the cout/cin at the start of the while loop, now you only need to write it once instead of twice

  • Use std::string to contain your string, then you can cout it without needing to repeat yourself:

#include <string>
const std::string welcomeMessage = "Bienvenido al cine. El precio...";
std::cout << welcomeMessage << std::endl;

2

u/AutoModerator 1d ago

Your posts seem to contain unformatted code. Please make sure to format your code otherwise your post may be removed.

If you wrote your post in the "new reddit" interface, please make sure to format your code blocks by putting four spaces before each line, as the backtick-based (```) code blocks do not work on old Reddit.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Discordbothost 1d ago

try typing a letter instead of an age. cin enters a failed state, so later reads won't wait for a new age and the loop can keep selling tickets. check whether each read succeeded before counting a customer; either stop or clear the error and discard the bad line.

1

u/flyingron 23h ago

10 points off for using namespace std.
10 points off for not indicating in the code what the magic number -137 means.
25 points off for not testing to see if the >> operation left cin in an error state causing the rest of the program to go off the rails.
10 points off for using endl when you don't have a reason to flush the stream.

-4

u/HyperWinX 1d ago

Its not english, im not sure how anyone could even read this
English is used for a reason

2

u/Mobile_Travel_1822 1d ago

hmm i get it, this might be part of the rating, well i´ll type everything in english from here so you all can read it, thank you

1

u/Mobile_Travel_1822 1d ago

well i think its not bad to learn one more lenguage

6

u/le_disappointment 1d ago

You speak English because it's the only language you know

I speak English because it's the only language you know

3

u/chibbe148 1d ago

bro, it's literally just variable names and some text in spanish, that's all bro

-3

u/HyperWinX 1d ago

When the only thing that i can understand is cin and cout there is not much tor review

-1

u/Desperate_Formal_781 1d ago

I don't understand how you post code in Spanish in an English sub and expect people to spend time reviewing your code, when you cannot even be bothered to translate it yourself.

-5

u/alfps 1d ago edited 1d ago

Your code translated Spanish → English and reformatted by Google's Gemini:

#include <iostream>
using namespace std;

int price = 80;
int childDiscount = -30; // childDiscount is the discount for children
int seniorDiscount = -35; // seniorDiscount = discount for older adults (seniors)
int age;
int customerCount = 0;
int seniorCount = 0;
int childCount = 0;
int childRevenue = 50;
int seniorRevenue = 45;
int regularRevenue = 80;

int main()
{
    cout << "Welcome to the cinema. The regular ticket price is $80, but you might be able to get a discount." << endl;
    cout << "Please enter your age: ";
    cin >> age;
    
    while (age != -137) {
        if (age < 12) {
            price += childDiscount;
            childCount = childCount + 1;
            cout << "Congratulations, kid, you get a discount." << endl;
        } else if (age >= 60) {
            price += seniorDiscount;
            seniorCount = seniorCount + 1;
            cout << "Congratulations, you get a discount." << endl;
        } else {
            cout << "Enjoy the show, it's the only thing you can get." << endl;
        }
        
        cout << "Your total to pay is: $" << price << "." << endl;
        price = 80;
        customerCount += 1;
        
        cout << "\n\n\n\nWelcome to the cinema. The regular ticket price is $80, but you might be able to get a discount." << endl;
        cout << "Please enter your age: ";
        cin >> age;
    }
    
    childRevenue = childRevenue * childCount;
    seniorRevenue = seniorRevenue * seniorCount;
    
    cout << "\n\nEnd of the day." << endl;
    cout << "Total customers: " << customerCount << endl;
    cout << "Total children: " << childCount << endl << "Money collected: $" << childRevenue << endl;
    cout << "Total seniors: " << seniorCount << endl << "Money collected: $" << seniorRevenue << endl;
    
    customerCount = customerCount - seniorCount - childCount;
    regularRevenue = regularRevenue * customerCount;
    
    cout << "Total regular adults: " << customerCount << endl << "Money collected: $" << regularRevenue << endl;
    
    int totalRevenue = regularRevenue + seniorRevenue + childRevenue;
    cout << "Total revenue: $" << totalRevenue;
    
    return 0;
}

The formatting is preserved in the presentation above because I extra-indented the code with 4 spaces.

This is great as a first program. :) Some possible improvements noted below.

Possible correctness improvement: output text.

Correctness trumps all other considerations.

And Gemini noted about its translation that

❞ In the final summary, the student wrote menores de edad (which legally means minors under 18) and mayores de edad (legal adults 18+), even though their if statements check for < 12 (children) and >= 60 (seniors). In the translation above, those were adapted to children and seniors to match their math, rather than translating the Spanish terminology literally.

I don't know Spanish at all but possibly this needs fixing.

Possible coding improvement.

It's a good idea to avoid global variables. For a lot of reasons they're consider Evil™.

So, better move those variables inside main.

Also consider replacing the using namespace std; directive with using declarations of what you actually use, like

using std::cin, std::cout, std::endl;

In the future, with larger code, it will help to avoid problems with name collisions.

Besides, every reviewer loves to comment on using namespace std;, that it's a bad habit, even if it's technically OK for small example programs.

Formatting improvement.

As exemplified by the translated code, the code is more clear when it is systematically formatted with indentation that reflects the logical structure.

I just do it manually when I write code, but programmers' editors and IDE's like Visual Studio can do it automatically for you.

Additionally there are free separate tools that can format code for you, e.g. AStyle for Windows.

-6

u/alfps 1d ago edited 1d ago

Re the anonymous unexplained downvote, note that an unexplained downvote is dishonest: this is the action of a dishonest person.

Presumably it's my several years' stalker, a mentally challenged OCD troll, possibly the DDDD... user. Anyway it's sabotage of the forum.

Oh neither I nor anyone else know what this serial downvoting is about. All we know is that it's a fucking idiot.

6

u/Wonderful-Habit-139 1d ago

I didn’t downvote, but I assume if they wanted to ask an LLM to translate they could do it themselves.

Probably not obvious whether the code improvement was yours or Gemini’s.

Also, the translation is apparently not faithful anyway, which matters to be able to correct OP.

1

u/Mobile_Travel_1822 1d ago

hey dude, i´d like to only take the good part out of this, he tried and did help, looked a good way to come with a improvement, and translationg might not be faitful cause i speak junk spanish, like i speak junk english

4

u/Wonderful-Habit-139 1d ago

I like that you’re communicating with your own words, it’s still very pleasant to read compared to LLMs.

Your English is not even close to being “junk”, you’re communicating well, keep going, and just keep learning.

-3

u/alfps 1d ago edited 1d ago

❞ I assume if they wanted to ask an LLM to translate they could do it themselves.

That's an ungood assumption for three reasons:

  • The OP didn't know it was doable.

  • It doesn't matter whether the OP wanted to present Spanish code, or not.

  • What matters is the ease with which English-speaking readers can review the code.


❞ the translation is apparently not faithful

It would be helpful if you can point out exactly how, other than what I already noted.

It's the opposite of helpful to just bandy about a vague ungoodness claim.


Re the downvoting of this comment, it's very dishonest to resort to downvoting. That makes me suspect the nonsensicality of your comment was not due to limited cognitive powers, but was merely dishonesty in action.

1

u/Wonderful-Habit-139 1d ago

You noted it and I pointed out that it’s a problem.

“In the translation above, those were adapted to children and seniors to match their math, rather than translating the Spanish terminology literally.”

Also, there’s no way OP doesn’t know LLMs can do that.

1

u/alfps 1d ago

❞ there’s no way OP doesn’t know LLMs can do that

You're saying the OP lied about that.

That's a very silly claim.

1

u/Wonderful-Habit-139 1d ago

That’s crazy. You got me.

1

u/alfps 1d ago

❞ You noted it [possibly misleading terms in the output] and I pointed out that it’s a problem.

It's a potential problem with the code, depending on the Spanish.

You give readers the incorrect impression that this code problem (if it is) is a problem with the answer.

That is untrue.

A review should point out serious problems. It's positive that an answer does that. Contrary to the misleading impression you convey and which, again, I suspect is not for lack of cognitive powers.

3

u/Im-not_good_at_names 1d ago

Dude what are you talking about

0

u/Mobile_Travel_1822 1d ago

a video taught me to use usning namespace std; ;-; didn´t know how bad it could be, also fot the global variables. thanks for the traduction, didn´t know it was doable.

1

u/n1ghtyunso 6h ago

there are millions of videos about c++ and also many many text-based learning sources about it as well.
Most of them are utterly terrible. Its really unfortunate for everyone learning it, sorry.
People in this subreddit do their best to undo and correct any of that damage, so you are in good hands here.