我是 C 编程的新手。我写了一个带有“for”循环的程序,它将接受两个 int 类型的输入 K 和 M 并打印出计算(除法中的散列函数)。如果我输入 q 或 Q 作为 K 或 M 的输入,那么它将退出。我将如何做?任何人都可以帮助我。
int main(){
int K;
int M;
for(;;)
{
printf("Enter the value of K: \n");
scanf("%d",&K);
printf("Enter the value of M: \n");
scanf("%d",&M);
printf("The Hash address of %d and %d is %d",K,M,K%M);
}
return system("pause");}
这会检查 scanf()
的返回值以查看扫描是否成功。如果不是,则清除缓冲区并检查指示程序应该退出的“q”。
getint()
接受提示消息和指向标志的指针。将标志设置为 -1 告诉调用者退出。
#include <stdio.h>
#include <math.h>
int getint ( char *prompt, int *result);
int main ( int argc, char* argv[])
{
int K, M;
int ok = 0;
do {
K = getint ( "\nEnter the value of K ( or q to quit)\n", &ok);
if ( ok == -1) {
break;
}
M = getint ( "\nEnter the value of M ( or q to quit)\n", &ok);
if ( ok == -1) {
break;
}
printf("\nThe Hash address of %d and %d is %d\n", K, M, K % M);
} while ( ok != -1);
return 0;
}
//the function can return only one value.
//int *result allows setting a flag:
// 0 the function is looping
// 1 the function is returning a valid int
// -1 the function returns and the program should exit
// the caller can see the flag of 1 or -1
int getint ( char *prompt, int *result)
{
int i = 0;
int n = 0;
*result = 0;
do {
printf("%s", prompt);
if ( scanf("%d",&n) != 1) {// scan one int
while ( ( i = getchar ( )) != '\n' && i != 'q') {
//clear buffer on scanf failure
//stop on newline
//quit if a q is found
}
if ( i != 'q') {
printf ( "problem with input, try again\n");
}
else {//found q. return and exit
*result = -1;
n = 0;
}
}
else {//scanf success
*result = 1;//return a valid int
}
} while ( *result == 0);
return n;
}
我是一名优秀的程序员,十分优秀!