我有一个基本的脚本,但我无法弄清楚如何让它通过一个关键词“退出”结束脚本的选项循环。如何让我的脚本循环并退出命令?
#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