令人难以置信的新编程我在第12行收到错误,说明我的break语句不在循环或切换中。任何人都可以解释我的错误在哪里以及如何解决它?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n1, n2, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
for(i=1; i <= n1 && i <= n2; ++i) {
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
if(n1==-1,n2==-1) break;
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
lcm = (n1*n2)/gcd;
printf("The LCM of two numbers %d and %d is %d.", n1, n2, lcm);
return 0;
}
答案 0 :(得分:0)
如果您是&#34;在第12行收到错误,说明我的break语句不在循环中或切换&#34;那么要么你有一个非常有缺陷的编译器,要么你发布了错误的代码。该代码存在少数问题,但错误位置的break
不是其中之一。
当您放错一些大括号时,通常会出现这种特殊的错误消息:
int i;
for (i = 0; i < 10; ++i)
printf("%d\n", i);
if (someCondition)
break;
这是因为,尽管看起来就像你正在突破循环,实际的break
语句不是 in 循环。只有printf
是。
就您提供的代码而言,有很多方法可以清理它:
DRY
原则进行输入,如果您正确构建代码段,则确实需要重复代码段。i
小的本地化循环之外,我几乎从不使用单字符变量名。if(n1==-1,n2==-1)
位。这并不是你认为它做的事情。逗号运算符将评估两个表达式,但完整表达式的结果是最右边的表达式。所以它有效if(n2==-1)
。为此,以下是 I 编写代码的方式:
#include <stdio.h>
#define ERR_NON_POS -1
#define ERR_INVALID -2
// Gets a single number.
// If non-positive or invalid, returns error (a negative value ERR_*).
// Otherwise, returns the (positive) number.
int getNumber(void) {
int number;
if (scanf("%d", &number) != 1) return -2;
if (number <= 0) return -1;
return number;
}
int main(void) {
// Infinite loop, we'll break from within as needed.
for (;;) {
printf("Enter two positive integers (a negative number will stop): ");
// Do it one at a time so a SINGLE negative number can stop.
int number1 = getNumber();
if (number1 == ERR_INVALID) {
puts("** Non-integral value entered");
break;
}
if (number1 == ERR_NON_POS) break;
int number2 = getNumber();
if (number2 == ERR_INVALID) {
puts("** Non-integral value entered");
break;
}
if (number2 == ERR_NON_POS) break;
// Work out greatest common divisor (though there are better ways
// to do this than checking EVERY possibility).
int gcd = 1;
for (int i = 2; (i <= number1) && (i <= number2); ++i) {
if (number1 % i == 0 && number2 % i == 0) {
gcd = i;
}
}
// Work out the lowest common multiple.
int lcm = number1 * number2 / gcd;
// Print them both and go get more.
printf("For numbers %d and %d, GCD is %d and LCM is %d.\n", number1, number2, gcd, lcm);
}
return 0;
}
而且,如果你想知道更有效的计算GCD的方法,你应该研究欧几里德的算法。这可以定义为(对于非负a
和b
):
gcd(a,b) = a if b is zero
gcd(b, a mod b) if b is non-zero
这意味着你可以拥有一个递归函数:
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
如果你强烈反对递归,那么就是迭代的:
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}