我是&lt; N + 1和i <= N不同?

时间:2016-01-20 07:15:42

标签: c++ c for-loop comparison

我曾经知道i <= Ni < N+1之间没有区别 但是,当我输入6 6进行编程时。

如果i <= N则打印

  

1 6 6
6 1 1
2 3 3
3 2 2

否则

  

1 6 6
6 1 1
2 3 3
3 2 2
3 2 2 2 3 3


我无法弄清楚它为何会产生影响

#include <iostream>
#include <cmath>

using namespace std;

typedef long long LNT;

LNT gcd(LNT a, LNT b)
{
    if( b == 0)
        return a;

    return gcd(b, a%b);
}

int main()
{
    LNT red, green;
    LNT GCD;
    cin >> red >> green;

    GCD = gcd(red, green);

    //for(LNT i = 1; i<sqrtl(GCD)+1; i++)
    for(LNT i = 1; i<=sqrtl(GCD); i++)   // <- This Line cause the difference 
    {
        if( GCD % i == 0)
        {
            cout << i << " " << red/i << " " << green/i <<endl;
            if( i != GCD/i )
            {
                LNT k = GCD/i;
                cout << k << " " << red/k << " " << green/k <<endl;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:15)

仅适用于整数值。当sqrtl返回long double时,如果它是小数,那么对于小数,如果您将原始分数与分数+1进行比较,其中另一个整数适合:

! 2 <= 1.5
2 < 1.5+1

答案 1 :(得分:2)

在这种情况下,

sqrtl返回long double您的假设:

  

i <= Ni < N+1

之间没有区别

错了。

答案 2 :(得分:0)

好吧,- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result { switch (result) { case MessageComposeResultCancelled: break; case MessageComposeResultFailed: { UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to send SMS!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [warningAlert show]; break; } case MessageComposeResultSent: break; default: break; } [self dismissViewControllerAnimated:YES completion:nil]; } i<=n之间没有区别,因为它们都只运行到i < n+1,但你所做的是n,返回long double并且对于它们不一定是一样的。