因此,最近我開始學習第一語言C++,並且正在編寫自己的程序以獲得一些練習。爲了讓你知道我有多遠,我剛剛介紹了課堂上的「if」和「else if」陳述。下面是代碼:Beginner C++ Help:if語句中的if語句
// Grade Calculator
#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
using namespace std;
int main()
{
float cutoffa, cutoffb, cutoffc, cutoffd, grade;
string firstname, lastname;
cout << setprecision(3) << fixed;
cout << "This program was made to test the \"if\" and \"else if\" statements.\n";
cout << "For this program you will be pretending to be a professor who is entering a student's grade.\n";
cout << "The first thing you will need to do is provide us with some basic information. Press enter when you are ready. \n";
cin.get();
cout << "What is the percent grade cut off (the lowest grade possible) for an A ? " ;
cin >> cutoffa;
cout << "What is the percent grade cut off for an B? " ;
cin >> cutoffb;
cout << "What is the percent grade cut off for an C? " ;
cin >> cutoffc;
cout << "What is the percent grade cut off for an D? " ;
cin >> cutoffd;
cout << "Enter the student's first name: ";
cin >> firstname;
cout << "Enter the student's last name: ";
cin >> lastname;
cout << "Enter the student's overall grade percentage: ";
cin >> grade;
if (grade >= cutoffa)
cout << firstname << " " << lastname << "'s Final Grade is " << grade << "%, which is an A! Congrats!";
else if (grade < cutoffa && grade >= cutoffb)
cout << firstname << " " << lastname << "'s Final Grade is " << grade << "%, which is a B! Pretty good, could be better though.";
else if (grade < cutoffb && grade >= cutoffc)
cout << firstname << " " << lastname << "'s Final Grade is " << grade << "%, which is a C! You're average - nothing more and nothing less.";
else if (grade < cutoffc && grade >= cutoffd)
cout << firstname << " " << lastname << "'s Final Grade is " << grade << "% which is D! Damn, you're stupid";
else if (grade < cutoffd)
cout << firstname << " " << lastname << "'s Final Grade is " << grade << "% which is an F! Have you considered dropping out?";
cin.get();
cin.get();
return 0;
}
程序應該是一個檔次的計算器這需要老師的檔次細分,並計算是否在課堂上有A,B,C,d,或F。我僅僅因爲練習的原因而這樣做,並且它與我的C++類沒有任何關係。
它運行的很好,所有,但我已經找出了一個問題:邁向最後,我把以下代碼行,適用於所有的條件語句(firstname和lastname是用戶進入他的字符串。第一/姓氏cutoffa是用於接收將切斷的檔次,用戶輸入):
if (grade >= cutoffa) cout << firstname << " " << lastname << "'s Final Grade is " << grade << "%, which is an A! Congrats!";
的問題是,如果有人有像傑克沙姆斯的名稱,它會打印出「傑克沙姆斯的最終成績是98%,這是A!恭喜!「。這裏的錯誤是「Shams's」,因爲它應該是「Shams」。就像我說的,我是初學者,這是我第一次使用if語句,所以如果有人能向我解釋如何得到它,那麼如果用戶姓氏以字母S結尾,程序會在S之前添加一個撇號,像這樣:Jake Shams'
體面的代碼,做得很好。我們更喜歡將[最小但完整的]代碼發佈到_here_上,因爲鏈接會死機,Stack Overflow上的所有問題都可以幫助未來的讀者,而不僅僅是您現在! –
謝謝我現在編輯帖子! – przm
你不必寫'else if(grade = cutoffb)',你可以寫'else if(grade> = cutoffb)',因爲當你到達else時,'grade
alain