I remember I had worked the "hardest" out of any student in my Spanish class as an undergrad. By hardest, I imply doing coursework submitted that went beyond what was assigned, including constantly participating in class and doing extraneous activities that coincided with the learning/student experience. The teacher gave me a B+. I was furious.
What I love about technical subjects such as math and science is there is no opinion. If your solution to a set of problems or concepts is accurate, it follows that that is your grade according to a default and objective scoring system. I understand any professor can wiggle out some damage to deflate a grade by arbitrarily taking points off for non-multiple choice questions (this is where you have open-ended, write-ins) but it's far more limited than in a liberal arts subject.
So, how do you achieve a 4.0? Like everything else in life, it's always a confluence of a sort: some luck, a college that grades an A as a 90 or higher, fair professors, a student putting in time to study, and of course how well you do on timed exams, to name a few.