這是我的代碼:
#include <stdio.h>
#include <conio.h>
int processChoice()
{
int choice = -1; //I need to execute this code without using any variable
printf("\nMake a Choice (1, 2, 3 or 0): ");
scanf("%d",&choice);
printf("%d",choice);
switch(choice)
{
case 0:
printf("\nExiting...\n");
break;
case 1:
printf("\nDrawing rectangle...\n");
break;
case 2:
printf("\nDrawing Right triangle...\n");
break;
case 3:
printf("\nDrawing isosceles triangle...\n");
break;
default:
printf("\n** Invalid Choice! **\n");
choice = -1;
}
return choice;
}
void showMenu()
{
printf("\nMenu:");
printf("\n1. Draw Rectangle");
printf("\n2. Draw Right triangle");
printf("\n3. Draw isosceles triangle");
printf("\n0. Exit program\n");
}
int main()
{
int x = -1;
do
{
showMenu();
}while(processChoice() != 0);
return 0;
}
這是我的代碼,我使用了一個變數“int Choice = -1;” 按照我導師的指導,我應該在不使用任何變數的情況下執行相同的代碼。
我期望在不使用任何變數的情況下執行相同的代碼。
uj5u.com熱心網友回復:
也許你的導師的意思是這個宣告主要
int x = -1;
未使用,應洗掉。
至于功能processChoice,無論如何您都需要輸入用戶的值。我看到唯一的可能性是在不使用變數的情況下通過以下方式使用函式撰寫函式getchar
int processChoice( void )
{
printf("\nMake a Choice (1, 2, 3 or 0): ");
switch( getchar() )
{
case '0':
printf("\nExiting...\n");
while ( getchar() != '\n' );
return 0;
case '1':
printf("\nDrawing rectangle...\n");
while ( getchar() != '\n' );
return 1;
case '2':
printf("\nDrawing Right triangle...\n");
while ( getchar() != '\n' );
return 2;
case '3':
printf("\nDrawing isosceles triangle...\n");
while ( getchar() != '\n' );
return 3;
default:
printf("\n** Invalid Choice! **\n");
while ( getchar() != '\n' );
return -1;
}
}
uj5u.com熱心網友回復:
/*I guess there are some communication barriers between you and your mentor XD
It's easy follow these corrections
*/
#include <stdio.h>
#include <conio.h>
int processChoice() {
int choice; //You're not required to use -1
printf("\nMake a Choice (1, 2, 3 or 0): ");
scanf("%d", & choice);
printf("%d", choice);
switch (choice) {
case 0:
printf("\nExiting...\n");
break; // Here the code should be intended by at least one tab. It is a part of clean code..
case 1:
printf("\nDrawing rectangle...\n");
break;
case 2:
printf("\nDrawing Right triangle...\n");
break;
case 3:
printf("\nDrawing isosceles triangle...\n");
break;
default:
printf("\n** Invalid Choice! **\n");
choice; // default initializing to zero it is unecessary to use -1 here.
}
return choice;
}
void showMenu() {
printf("\nMenu:");
printf("\n1. Draw Rectangle");
printf("\n2. Draw Right triangle");
printf("\n3. Draw isosceles triangle");
printf("\n0. Exit program\n");
}
int main() {
// Delete again initializing of this here aka int x = -1;
do {
showMenu();
} while (processChoice() != 0);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533713.html
標籤:C变量开关语句函数定义
