#c
#c
Вопрос:
Проблема: Стипендиальный благотворительный фонд, часть 2 (fund2.c)
Как мне вернуться в главное меню и добавить счетчик для общего количества сделанных пожертвований и инвестиций, вот что я получил?
Затем ваша программа должна предоставлять пользователю следующие опции:
- Сделайте пожертвование
- Сделайте инвестиции
- Распечатать баланс фонда
- ВЫЙТИ
#включить <stdio.h> #включить <stdlib.h>
//main functions
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!n");
printf("What is the initial balance of the fundn");
scanf("%d", amp;fund);
int ans;
printf("What would you like to do?n");
printf("t1- Make a Donationn");
printf("t2- Make an investmentn");
printf("t3- Print balance of fundn");
printf("t4- Quitn");
scanf("%d", amp;ans);
if (ans == 1) {
printf("How much would you like to donate?n");
scanf("%d", amp;donation);
}
if (ans == 2) {
printf("How much would you like to invest?n");
scanf("%d", amp;investment);
return main();
}
if (ans == 3) {
total = donation fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amountn");
return main();
}
else {
printf("The current balance is %dn", total);
printf(" There have been %d donations and %d investments.n", tdonations, tinvestments);
}
}
if (ans == 4) {
printf("Type 4 to quitn");
}
else {
printf("Not a valid option.n");
}
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?n");
scanf("%d", amp;donation);
return main();
case 2:
printf("How much would you like to investn");
scanf("%d", amp;investment);
return main();
case 3:
printf("The current balance is %dn", total);
printf(" There have been %d donations and %d investments.n", tdonations, tinvestments);
return main();
case 4:
break;
}
return 0;
}
Комментарии:
1. Вы знаете, как использовать цикл? Кроме того,
main
повторный вызов является дурным тоном.2. Я не знаю, как вернуть его в меню и заставить его отслеживать пожертвования и инвестиции
3. Вы никогда не называете
main
себя в коде. Никогда. Никаких исключений, никогда. Вы НЕ называетеmain
себя. Перечитайте конспекты занятий, учебное пособие или книгу по теме «Операторы цикла».
Ответ №1:
Вы должны поместить в цикл ту часть, которую хотите повторить, используя переменную, чтобы решить, когда остановиться.
вот пример, также в структуре switch вы должны указать опцию по умолчанию, возможно, чтобы предупредить пользователя о том, что введенная им опция недействительна.
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!n");
printf("What is the initial balance of the fundn");
scanf("%d", amp;fund);
//loop until the user decide so
int exit = 0;
while(exit == 0){
int ans;
printf("What would you like to do?n");
printf("t1- Make a Donationn");
printf("t2- Make an investmentn");
printf("t3- Print balance of fundn");
printf("t4- Quitn");
scanf("%d", amp;ans);
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?n");
scanf("%d", amp;donation);
break;
case 2:
printf("How much would you like to investn");
scanf("%d", amp;investment);
break;
case 3:
total = donation fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amountn");
}
else {
printf("The current balance is %dn", total);
printf(" There have been %d donations and %d investments.n", tdonations, tinvestments);
}
break;
case 4:
exit = 1;
break;
default:
printf("Incorrect optionn");
break;
}
}
return 0;
}
Комментарии:
1. Как мне добавить счетчик, который отслеживает общее количество пожертвований и инвестиций
2. Вы создаете переменную и инициализируете ее нулем, @TheOnion . Вы увеличиваете каждый раз, когда пользователь делает инвестиции или пожертвования.