Здравствуйте! Вы знакомы с языком программирования с++? Не могли бы вы дать оценку моей программе на данном языке программирования ? Буду очень благодарна😍 #include<string> #include - вопрос №1733254

<iostream>using namespace std; int main(){​char a;​int r;​string k;​​​​​cout << "Please, type your name:\n";​​cin >> k;​​cout << k << ", Hello! This is Your ideal diet test. Press enter for start, or press esc button to start this console application. Write OK \n";​cin >> k;​cout << "Answer to the questions and get your ideal diet!" << endl;​r = 0;​question1:​cout << "Which body type do you have? a) ectomorphic b)mesomorphic c)endomorphic " << endl;​cin >> a;​if (a == 'a')​{​​r = r + 1;​}​else if (a == 'b')​{ r = r + 2;​}​else if (a == 'c')​{ r = r + 3;​}​else​{​​cout << "enter the correct data, please!" << endl;​​cout << "Here is information about body type :" << endl;​​cout << " The ectomorph can be easily spotted in any weight room. They are often below the average weight for their height and have a skinny appearance. Ectomorphs tend to have very high metabolisms and often complain of relentless eating with little to no weight gain." << endl;​ cout << "The endomorphic body type is the complete opposite of an ectomorph. This individual will usually be larger in appearance with heavier fat accumulation and little muscle definition. They find it hard to drop the weight even though they try several diets or workout programs." << endl;​ cout << "Everyone recognizes the mesomorph. He is the high school jock that seemed to put on muscle just by looking at weights while also maintaining a very lean physique. The mesomorph is somewhat in between the ectomorph and the endomorph and as such, display qualities from both. He has a larger frame (bone structure) as the endomorph does, but a low body fat percentage as the ectomorph has. You could say this is the aspiring body type that everybody wants." << endl;​​goto question1;​}question2:​cout << "Do you often eat starchy foods, sweets or cakes? a) Yes b)No " << endl;​cin >> a;​if (a == 'a')​{​​r = r + 2;​}​else if (a == 'b')​{​​r = r + 1;​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question2;​}question3:​cout << "Do you often feel nervous? Does food help you to overcome stress? a)no b)yes, but I overcome stress without food c)yes I am often stressed and, I overcome stress with food " << endl;​cin >> a;​if (a == 'a')​{ r = r + 0;​}​else if (a == 'b')​{ r = r + 0;​}​else if (a == 'c')​{ r = r + 2;​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question3;​}question4:​cout << "How much water do you drink per day? a)Less that 1L b)1Land more c)2L and more" << endl;​cin >> a;​if (a == 'a')​{ r = r + 2;​}​else if (a == 'b')​{ r = r + 1;​} ​else if (a == 'c')​{ r = r + 0; ​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question4;​}question5:​cout << "How do you sleep? a)good b)not well " << endl;​cin >> a;​if (a == 'a')​{ r = r + 0;​}​else if (a == 'b')​{ r = r + 2;​}​​else​{​​cout << "enter the correct data, please!" << endl;​​goto question5;​}question6:​cout << "How often do you eat during a day? a) Less than three times b)3 times c)More than 3 times " << endl;​cin >> a;​if (a == 'a')​{ r = r + 3;​}​else if (a == 'b')​{r = r + 2;​}​else if (a == 'c')​{r = r + 1;​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question6;​}question7:​cout << "How much do you eat? a) Big portions b)Small portions " << endl;​cin >> a;​if (a == 'a')​{r = r + 2;​}​else if (a == 'b')​{r = r + 0;​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question7;​}question8:​cout << "What of the following variants suits better to your breakfast? a) Porriage and a drink b)Fried food c)A drink only" << endl;​cin >> a;​if (a == 'a')​{r = r + 1;​}​else if (a == 'b')​{r = r + 2;​}​else if (a == 'c')​{r = r + 1;​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question8;​}question9:​cout << "How often do you do physical exercises? a)Often b)Not often c)I do not do sports " << endl;​cin >> a;​if (a == 'a')​{r = r + 0;​}​else if (a == 'b')​{r = r + 1;​}​else if (a == 'c')​{r = r + 2;​}​else​{​​cout << "enter the correct data, please!" << endl;​​goto question9;​}cout << "your score is " << r << endl; cout <<" Count your score" << endl; cout << "If your score is less than 8 score, you need to include products like milk, high density fruits, like avocado and peanut butter." <<endl; cout << "If you have score more than 8 but less than 14, you are already have a good diet. Just keep staying healthy and eat more fruits and vegetables " <<endl; cout <<" If you have more than 14 scores, you need to make changes in your diet. Do not eat junk food ( fast food) and eat your meal in little portions several times a day. Try to eat healthy, low colorized food" << endl; ​cout << "Press enter if you want to start the test again " << endl; cin >> a;​if (a == 'a')​{​​r = r + 1;​}​goto question1; ​system("pause");​return 0;​}
29.11.15
2 ответа

Лучший ответ по мнению автора

Здравствуйте.
Мда, код нечитаем.

Тем не менее, если отформатировать и разобраться, то можно сказать следующее:

1. 'press esc button to start this console application' — не играет в данном случае никакой роли.
Для cin подходит Enter как окончание ввода (при этом нужно хоть 1 символ ввести), или Ctrl-C как прерывание программы.

2. Использование goto — спорный момент. Да, есть случаи когда goto может быть полезен, но использовать его нужно очень аккуратно. У Вас, например, первая метка поставлена неправильно (см п.6), что приводит к ошибке подсчета баллов при повторных тестах.
В реальных проектах goto очень часто приводит к усложнению процесса отладки и к возникновению ошибок. Особенно, если используется много переходов вида

if() goto l1;
else goto l2;

то это можете считать Плохим Делом (Bad Thing) ©

Поэтому нужно очень аккуратно использовать goto, чтобы не пропустить, например, инициализацию какого-нибудь объекта или переменной.

3. Конструкция вида    r = r + 0; фактически не несет смысловой нагрузки.

4. Множество конструкций вида
if () { }
else if () { }
else if () { }
лучше заменять на switch/case если это возможно (в данном случае это возможно)

5. В конце — Вы уже подсчитали баллы и вывели результат, можно было сразу дать совет (а не писать, если у Вас меньше 8 баллов, то то-то и то-то и пр, можно было на основе набранных баллов вывести только соответствующий совет)

6. Последнее сообщение в тесте — «нажмите Enter, если хотите начать тест заново»
А как выйти из теста?  Про ctrl-c Вы не написали, а по коду — тест будет начинаться заново до бесконечности, если программу не прервать.
Получается что пользователь должен знать про ctrl-c или закрыть окно с Вашей программой.

Это ладно, но далее чистая ошибка.
Если ввели символ 'a', при этом зачем-то прибавляется 1 балл в тест.
И потом программа перекидывается на метку question1, но и r не сбрасывается в 0 (r инициализируется в 0 перед меткой)! Вот Вам пример ошибки с оператором goto.

В результате, что бы Вы не ввели на фразу «Press enter if you want to start the test again », при повторном прохождении теста результат подсчета баллов будет совсем неправильный.

(для примера — если все время на все вопросы отвечать 'a', при первом проходе получим 11 баллов, при втором — уже 23, при третьем — 35 и т.п.)

Удачи Вам! И просьба обратить внимание на указанные моменты, чтобы избежать ошибок в будущем!
30.11.15
Лучший ответ по мнению автора

Другие ответы

тут может быть только одна оценка — абсолютно не читаемо

можете попробовать воспользоваться вот этим сервисом - http://pastie.org/

29.11.15

Глеб Черняк

Читать ответы

Олег Николаевич

Читать ответы

Alexander

Читать ответы
Посмотреть всех экспертов из раздела Технологии
Пользуйтесь нашим приложением Доступно на Google Play Загрузите в App Store