2016-10-20 4 views
0

xcode/suft에 내 딸을위한 수학 퀴즈 앱을 쓰고 있습니다.
특히, 임의로 생성 된 두 번째 숫자에 대해 더하거나 뺄 음수를 적어도 하나 이상 포함하는 질문을 만들고 싶습니다.
두 개의 양수가 될 수 없습니다.퀴즈의 무작위 (양수 및 음수) 숫자

(-45) 12 감산 무엇인가?
23 마이너스 (-34)는 무엇입니까?

숫자를 생성하는 구문을 올바르게 사용하기 위해 분투하고 있으며, 그 숫자가 음수인지 양수인지를 결정하는 데 어려움을 겪고 있습니다.

다음 두 번째 문제는 문제가 더하기 또는 빼기 일 경우 임의 화됩니다.

+0

명확한 숫자 조합을 원하십니까? 'a <0'또는 'b <0'중 하나 인 'a + b'조합? –

+1

예. 기본적으로 숫자는 범위 내에서 -50에서 50 사이의 임의 숫자입니다. NumberB는 동일합니다. 그러나 두 개의 양수가 생성되면 음수 (NumberB = NumberB * -1)로 전환해야합니다. –

+0

죄송합니다. 내 의견은 아무 이유없이 계속 전송되었습니다.) –

답변

1

내 시도입니다. 놀이터에서 이것을 실행 해보면, 원하는 결과를 얻을 수있을 것입니다. 나는 충분히 깨끗한 것을 만들었 으면 좋겠다. ...

//: Playground - noun: a place where people can play 

import Cocoa 


let range = Range(uncheckedBounds: (-50, 50)) 

func generateRandomCouple() -> (a: Int, b: Int) { 
    // This function will generate a pair of random integers 
    // (a, b) such that at least a or b is negative. 

    var first, second: Int 

    repeat { 
     first = Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound))) - range.upperBound 
     second = Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound))) - range.upperBound 
    } 
     while (first > 0 && second > 0); 

    // Essentially this loops until at least one of the two is less than zero. 

    return (first, second) 
} 


let couple = generateRandomCouple(); 
print("What is \(couple.a) + (\(couple.b))") 
// at this point, either of the variables is negative 


// I don't think you can do it in the playground, but here you would read 
// her input and the expected answer would, naturally, be: 

print(couple.a + couple.b) 

어떤 경우라도, 설명을 요청할 수있다. 행운을 빕니다 !

+0

아 남자. 고맙습니다. 이 코드를 코드에 삽입하고 필요한 사항을 변경합니다. 코코아도 고려하지 않았어. –

+1

매우 감사드립니다. 평화. –

+0

@ElephantBoy Cocoa는 iOS에서는 사용할 수 없지만 Foundation 만 필요합니다 ('arc4random'의 경우). – NobodyNada

1

반복 숫자 그리기없이이를 해결할 수 있습니다.

  1. 이 숫자가 음수이면
  2. 양 또는 음의 임의의 숫자를 그리기 : 동일한 범위에서 다른 번호를 그리고 쌍을 반환 아이디어이다.
  3. 숫자가 양수이면 음수로 제한된 범위에서 두 번째 숫자를 그립니다. ...

    let pair = (-10 ... 100).randomPair 
    

    을 지금

    extension CountableClosedRange where Bound : SignedInteger { 
    
        /// A property that returns a random element from the range. 
        var random: Bound { 
         return Bound(arc4random_uniform(UInt32(count.toIntMax())).toIntMax()) + lowerBound 
        } 
    
        /// A pair of random elements where always one element is negative. 
        var randomPair: (Bound, Bound) { 
         let first = random 
         if first >= 0 { 
          return (first, (self.lowerBound ... -1).random) 
         } 
         return (first, random) 
        } 
    } 
    

    그냥 쓸 수 있습니다 ... 그리고 하나 개의 요소가 부정적 보장 임의의 튜플을 얻을 :

여기에 구현입니다.

+0

그건 꽤 깔끔한 접근법입니다. 나는 그것을 좋아한다. –

+0

두 스타일 모두에 투표했습니다. –

관련 문제