我有一個基本的腳本,但我無法弄清楚如何讓它通過一個關鍵詞「退出」結束腳本的選項循環。如何讓我的腳本循環並退出命令?
#include<stdio.h>
#include<math.h>
#include<string.h>
int gcd(int a, int b) {
while(0!=b) { int r = a % b; a=b; b=r; }
return a;
}
int input(char* prompt) {
int res;
printf("%s: ", prompt);
scanf("%d", &res);
return res;
}
main()
{
int add,sub,mul,dd;
int add1,sub1,mul1,dd1;
int a,b,c,d;
a=input("Please enter the numerator for your first equation");
b=input("Please enter the denominator for your first equation");
c=input("Please enter the numerator for your second equation");
d=input("Please enter the denominator for your second equation");
add=(a*d+b*c);
add1=(b*d);
int fac = gcd(add, add1);
add /=fac;
add1 /=fac;
printf("\The sum of your fractions is: %d/%d",add,add1);
sub=(a*d-b*c);
sub1=(b*d);
int red = gcd(sub, sub1);
sub /=red;
sub1 /=red;
printf("\nThe difference of your fractions is: %d/%d",sub,sub1);
mul=(a*c);
mul1=(b*d);
int red1 = gcd(mul, mul1);
mul /=red1;
mul1 /=red1;
printf("\nThe product of your fractions is: %d/%d",mul,mul1);
dd=(a*d);
dd1=(b*c);
int red2 = gcd(dd, dd1);
dd /=red2;
dd1 /=red2;
printf("\nThe quotient of your fractions is: %d/%d",dd,dd1);
}
這個想法是讓用戶能夠連續嘗試功能,即使在給出一組結果後。據說,用戶應該能夠在第一個分子問題中鍵入「quit」,腳本將結束。有人可以幫我解決這個問題嗎?
更新4:
#include<stdio.h>
#include<math.h>
#include<string.h>
#define LINE_SIZE 100
int gcd(int a, int b) {
while(0!=b) { int r = a % b; a=b; b=r; }
return a;
}
int input(char* prompt) {
int res;
char line[LINE_SIZE];
printf("%s: ", prompt);
if (fgets(line, LINE_SIZE, stdin) == NULL)
{
exit(0);
}
if (strncmp(line, "quit", 4) == 0)
{
exit(0);
}
if (sscanf(line, "%d", &res) != 1)
{
}
return res;
}
void computeAndPrint()
{
main();
{
int add,sub,mul,dd;
int add1,sub1,mul1,dd1;
int a,b,c,d;
a=input("Please enter the numerator for your first equation");
b=input("Please enter the denominator for your first equation");
c=input("Please enter the numerator for your second equation");
d=input("Please enter the denominator for your second equation");
add=(a*d+b*c);
add1=(b*d);
int fac = gcd(add, add1);
add /=fac;
add1 /=fac;
printf("\The sum of your fractions is: %d/%d",add,add1);
sub=(a*d-b*c);
sub1=(b*d);
int red = gcd(sub, sub1);
sub /=red;
sub1 /=red;
printf("\nThe difference of your fractions is: %d/%d",sub,sub1);
mul=(a*c);
mul1=(b*d);
int red1 = gcd(mul, mul1);
mul /=red1;
mul1 /=red1;
printf("\nThe product of your fractions is: %d/%d",mul,mul1);
dd=(a*d);
dd1=(b*c);
int red2 = gcd(dd, dd1);
dd /=red2;
dd1 /=red2;
printf("\nThe quotient of your fractions is: %d/%d",dd,dd1);
printf("\n");
}
int main();
{
while (1)
{
computeAndPrint();
}
return 0;
}
在這種情況下,需要用'%s'代替'%D',存儲在數組的值,然後將其與「跳槽」比較從輸入讀,使用'的strcmp()'。如果單詞不匹配,可以使用'atoi'將其轉換爲整數。 – ddz