Member 13708328 Ответов: 2

Как мне заставить мое программирование на языке Си для функций работать должным образом


У меня есть 2 проблемы.

1) I have 3 menu inputs as options 1, 2 and 3 that work fine with option 4 being the take a trip option. This option #4 allows you to say how many miles your trip will be. It operates as intended even letting me do multiple trips while it adds to a running total. I'm having a hard time in getting it to recognize the other options after I chose option 4. I see that if use return result at the end of option #4 if will allow me to use regular menu but it only allows me to run a running total twice when I go this route even with a loop. If I take away the return result on option #4 it will keep allowing the running total to run but won't allow me to access the other options on the menu.


2) Когда я могу получить доступ к другим опциям меню, когда у меня есть только возможность сделать running total на 2 номера, выбор другого варианта, чтобы сказать redo price of gas или miles per gallon, не сохраняет текущие общие данные, которые я имел от использования опции #4.

Вот мой код ниже...мы обязаны использовать функции и держать основные очень голые кости


#define _CRT_SECURE_NO_WARNINGS
#define PAUSE system("pause")
#define FLUSH myFlush()
#define CLS system("cls")
#include<stdio.h>
#include<stdlib.h>

//prototype functions here
void displayMenu(double choice);
void displayOutput(double pricePerGallon, double milesPerGallon, double getMilesBeginning, double milesDriven, double milesCurrent, double totalCost);
int getChoice(double milesBeginning, double pricePerGallon, double milesPerGallon);
double getMilesBeginning(double milesBeginning, double pricePerGallon, double milesPerGallon, double milesDriven, double milesCurrent, double totalCost);
double getMilesPerGallon(double milesPerGallon);
double getPricePerGallon(double pricePerGallon);
void myFlush();

main() {
	int choice;
	double milesBeginning = 0, pricePerGallon = 0, milesPerGallon = 0, milesCurrent = 0, milesDriven = 0, totalCost = 0;
	do {
		choice = getChoice(milesBeginning, pricePerGallon, milesPerGallon);
		switch (choice) {
		case 1:
			milesBeginning = getMilesBeginning(milesBeginning,pricePerGallon, milesPerGallon, milesDriven, milesCurrent, totalCost);
			break;
		case 2:
			pricePerGallon = getPricePerGallon(pricePerGallon);
			break;
		case 3:
			milesPerGallon = getMilesPerGallon(milesPerGallon);
			break;
		case 4:
			displayOutput(pricePerGallon, milesPerGallon, milesBeginning, milesCurrent, milesDriven, totalCost);
			break;
		case 5:
			break;
		default:
			printf("\nPlese pick a valid choice!!!\n\n");
			PAUSE;
			break;

		}//end switch 

	} while (choice != 5);

}//end of main

void displayMenu(double choice) {
	CLS;
	printf("\n1. Enter Beginning Mileage.\n");
	printf("2. Enter Price per Gallon.\n");
	printf("3. Enter Miles per Gallon.\n");
	printf("4. Take a trip.\n");
	printf("5. Quit the program.\n");
	printf("\n\n");
	printf("Enter your selection: ");
	
}//end displayMenu

void displayOutput(double pricePerGallon, double milesPerGallon, double milesBeginning, double milesDriven, double milesCurrent, double totalCost) {
	double result = 0;
	int choice = 0;

	if (milesBeginning <= 0 || pricePerGallon <= 0 || milesPerGallon <= 0) {
		printf("You must enter a positive value for choices 1, 2 & 3 before you proceed.\n"); FLUSH;
		return 0;
	}//end if

	do  {
		if (milesDriven <= 0) {
			CLS;
			printf("Please enter amount of miles traveled for this trip: ");
			scanf("%lf", &milesDriven); FLUSH;
			printf("You have traveled %.2lf miles for this trip.\n", milesDriven);

			printf("Your current mileage is %.2lf miles.\n", milesBeginning += milesDriven);
			printf("Your current trip cost $%.2lf.\n", (totalCost += (milesDriven / milesPerGallon) * pricePerGallon));
			
			PAUSE;
			
		}//end if
		/*else if (choice != 4) {
			displayMenu(choice);
			scanf("%c", &choice);
			CLS;
			return result;
		}*/

		


		do {
			displayMenu(choice);
			scanf("%c", &result);
			CLS;
			printf("Please enter amount of miles traveled for your next trip:  ");
			scanf("%lf", &milesDriven);
			printf("You have traveled %.2lf miles for this trip.\n", milesDriven);
			printf("Your mileage for this current trip is %.2lf miles.\n", milesDriven);
			printf("Your cost for this current trip is $%.2lf.\n", (milesDriven / milesPerGallon) * pricePerGallon);
			printf("Your Total mileage is %.2lf miles.\n", milesBeginning += milesDriven);
			printf("Your Total trip cost $%.2lf.\n", totalCost += (milesDriven / milesPerGallon) * pricePerGallon);
			PAUSE;
			displayMenu(choice);
			scanf("%c", &result);
			return choice;
			
		
		} while (choice != 5);//end of do loop
		

	} while (choice != 5);//end of do loop

	} //end of displayOutput

double getMilesBeginning(double milesBeginning, double pricePerGallon, double milesPerGallon, double milesDriven, double milesCurrent, double totalCost) {
	double result = milesBeginning;
	char choice; 
	CLS;
	printf("Your beginning mileage is %.2lf miles.\n", milesBeginning);
	printf("Press 'C' to change: ");
		scanf("%c", &choice); FLUSH;
		if (toupper(choice) != 'C')
			return result;
		else if (result > 0) {
			printf("You only get to enter a beginning number once.\n");
			printf("Please move on to other selections."); FLUSH;
		}
		else {
			printf("Please enter the beginning mileage:  ");
			scanf("%lf", &result);
			while (result <= 0) {
				printf("Please enter a positive number of beginning mileage.\n");
				printf("This program can't run until you do this.\n");
				printf("Please enter the beginning mileage:  ");
				scanf("%lf", &result); FLUSH;
			}//end while
		}//end else
		return result;
}//end getMileageBeginning

double getMilesPerGallon(double milesPerGallon) {
	double result = milesPerGallon;
	char choice;
	CLS;
	printf("Your Miles Per Gallon is %.2lf miles per gallon.\n", milesPerGallon);
	printf("Press 'C' to change: ");
	scanf("%c", &choice); FLUSH;
	if (toupper(choice) != 'C')
		return result;
	else {
		printf("Please enter the Miles Per Gallon:  ");
		scanf("%lf", &result); FLUSH;
		while (result <= 0) {
			printf("Please enter a positive Miles Per Gallon.\n");
			printf("This program can't run until you do this.\n");
			printf("Please enter the Miles Per Gallon:  ");
			scanf("%lf", &result); FLUSH;
		}//end while
	}//end else

	return result;
}//end get MilesPerGallon


double getPricePerGallon(double pricePerGallon) {
	double result = pricePerGallon;
	char choice;
	CLS;
	printf("Your Price Per Gallon is %.2lf per gallon.\n", pricePerGallon);
	printf("Press 'C' to change: ");
	scanf("%c", &choice); FLUSH;
	if (toupper(choice) != 'C')
		return result;
	else {
		printf("Please enter the Price Per Gallone:  ");
		scanf("%lf", &result); FLUSH; 
		while (result <= 0) {
			printf("Please enter a positive Price Per Gallon.\n");
			printf("This program can't run until you do this.\n");
			printf("Please enter the Price Per Gallon:  ");
			scanf("%lf", &result); FLUSH;
		}//end while
	}//end else
	return result;
}//end getPricePerGallon

int getChoice(double milesBeginning, double pricePerGallon, double milesPerGallon) {
	int result, choice = 0;
	//double pricePerGallon = 0, milesDriven = 0, milesPerGallon = 0, milesCurrent = 0, milesBeginning = 0;
	displayMenu(choice);
	scanf("%i", &result); FLUSH;

	return result;

}//end of getChoice

void myFlush() {    // this consumes all extra crap from the keyboard buffer
	while (getchar() != '\n');
} // end myFlush


Что я уже пробовал:

В течение последних нескольких дней я пытался изменить ситуацию во всех отношениях. Иногда у меня получается одно, а другое-нет. Любой совет очень ценится.

Mohibur Rashid

Дамп кода. Вы пробовали отладку?

2 Ответов

Рейтинг:
2

Patrice T

Где и когда вы обновляетесь milesDriven и totalCost в главном?
Когда вы не понимаете, почему ваш собственный код не делает того, что вы ожидаете, самое время запустить отладчик, чтобы посмотреть, что происходит.

Существует инструмент, который позволяет вам видеть, что делает ваш код, его имя отладчик Это также отличный инструмент обучения, потому что он показывает вам реальность, и вы можете увидеть, какие ожидания соответствуют реальности.
Когда вы не понимаете, что делает ваш код или почему он делает то, что он делает, ответ таков: отладчик.
Используйте отладчик, чтобы увидеть, что делает ваш код. Просто установите точку останова и посмотрите, как работает ваш код, отладчик позволит вам выполнять строки 1 на 1 и проверять переменные по мере их выполнения.

Отладчик - Википедия, свободная энциклопедия[^]

Освоение отладки в Visual Studio 2010 - руководство для начинающих[^]
Базовая отладка с помощью Visual Studio 2010 - YouTube[^]
Отладчик здесь, чтобы показать вам, что делает ваш код, и ваша задача-сравнить с тем, что он должен делать.
В отладчике нет никакой магии, он не находит ошибок, он просто помогает вам. Когда код не делает того, что ожидается, вы близки к ошибке.


Рейтинг:
1

CPallini

Ваш вариант 4 ('Take a trip') должен просто позволить пользователю ввести информацию о поездке.
Вы должны ввести еще одну опцию, чтобы показать текущий выход.