我在Swift与Java中的代码. Swift给出了一个错误,但是Java没有给出一个错误.有什么区别吗? [英] My code in Swift vs. Java. Swift gives an error but Java doesn't. Are there any differences?

查看:69
本文介绍了我在Swift与Java中的代码. Swift给出了一个错误,但是Java没有给出一个错误.有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写一个应用程序,它将查找数字的主要因素.我正在用Swift编写应用程序,但是如果我将"num"设置为偶数而不是奇数,它将给我一个错误.该错误在代码的第5行显示Execution was interrupted, reason: EXC_BAD_INSTRUCTION code=EXC_l386_INVOP, subcode=0x0.

So I'm writing an app that will find the prime factors of a number. I'm writing the app in Swift but it gives me an error if i set "num" to an even number but not an odd number. The error says, Execution was interrupted, reason: EXC_BAD_INSTRUCTION code=EXC_l386_INVOP, subcode=0x0 on the 5th line of code.

这是Swift代码:

var num = 16

for i in 2...(num/2)-1 {

    if ((num % i) == 0) {
        var isPrimeFactor = true

        for l in 2...i-1 {
            if ((i%l) == 0) {
                isPrimeFactor = false;
            }//end if
        }//end for

        if (isPrimeFactor == true) {
            i
        }//end if

    }//end if

}//end for

这是Java代码(我认为是Swift代码的精确副本):

Here's the Java code(that I thought was an exact copy of the Swift code):

int num = 16;

for (int i=2; i<num/2; i++) {
    if (num%i == 0) {
        boolean isPrimeFactor = true;

        for (int l=2; l<i; l++) {
            if ((i%l) == 0) {
                isPrimeFactor = false;
            }
        }

        if (isPrimeFactor == true) {
            System.out.println(i);
        }
    }
}

此外,Apple是否在for循环中摆脱了..?我也使用这些错误.

Also, did Apple get rid of the .. in for loops? I get an error using those too.

哇.我发现我的代码只需要..<而不是... num-1来工作.感谢所有贡献者的所有帮助!

Wow. I figured out that my code just needed the ..< instead of ...num-1 to work. Thanks for all the help to all the contributed!

推荐答案

不,苹果没有摆脱for in循环.

No, apple didn't get rid of the for in loops.

您的问题是该行:

 for l in 2...i-1 {

因为如果i-1小于2,则会发生此错误.因此,如果i-1等于或大于2,则需要进行检查.请检查此代码以证明错误:

Because if i-1 is less than 2, this error occurs. So you need to make a check, if i-1 is equal or greater than 2. check this code to prove the error:

for l in 2...2 { //No error
for l in 2...1 { //error

因此,如果您想保留自己的代码,我会做类似的事情:

So I would make something like that, if you want to keep your code:

if(i-1 >= 2){
    for a in 2...i-1 {
        if ((i%a) == 0) {
            isPrimeFactor = false
        }//end if
    }//end for
}

您在这里也有错误:

 if (isPrimeFactor == true) {
            i
        }//end if

您需要将i包裹到println(i)中或将其删除.

You need to either wrap the i into an println(i) or remove it.

这篇关于我在Swift与Java中的代码. Swift给出了一个错误,但是Java没有给出一个错误.有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆