2015-01-10 2 views
0

다음 코드를 if 문에서 스위치로 변경하는 방법. (0,0,0,1,1,1,2,2,2,2) 아래의 시퀀스에 따라 속도 [0]을 증가시킬 수 있습니까? 변수 노드는 유형 객체입니다.if 문을 스위치로 변경하는 방법

if (node->speed[0] > system->velocity) 
    node->speed[0] = pSystem->velocity; 
else if (node->speed[0] < pSystem->nVelocity) 
    node->speed[0] = pSystem->nVelocity; 
if (node->speed[1] > pSystem->velocity) 
    node->speed[1] = pSystem->velocity; 
else if (node->speed[1] < pSystem->nVelocity) 
    node->speed[1] = pSystem->nVelocity; 
if (node->speed[2] > pSystem->velocity) 
    node->speed[2] = pSystem->velocity; 
else if (node->speed[2] < pSystem->nVelocity) 
    node->speed[2] = pSystem->nVelocity; 
+0

스위치, 나는 그렇게 생각하지 않지만 for 루프가 도움이 될 수 있습니다. – Jasen

+0

괜찮 았어 for 루프를 사용하는 방법, 어쨌든 더 나은 코드를 만들 수 있습니까 –

+0

당신이 스위치 진술에 사용할 수 없습니다. 가능하지 않은 일을하는 법을 알려 주셔서 고맙습니다. –

답변

0

switch 문과 실제로는 맞지 않지만 for 루프가 적합합니다.

for (int i = 0; i<3 ; ++i) 
    if (node->speed[i] > system->velocity) 
    node->speed[i] = pSystem->velocity; 
    else if (node->speed[i] < pSystem->nVelocity) 
    node->speed[i] = pSystem->nVelocity; 
+1

OP의 코드는'system'을 한 번만 사용하고'pSystem'은 열 번만 사용합니다. OP만이 의도적 또는 오판 일 경우 알려줄 수 있습니다. – TonyK

1

이 비교에 switch을 할 의미있는 방법이 없다,하지만이 같은 뭔가를 다시 작성할 것 (첫 번째 줄에 "시스템이"실제로 "pSystem"인 것을 가정) :

int clamp(int x, int min, int max) 
{ 
    if (x < min) 
     return min; 
    if (x > max) 
     return max; 
    return x; 
} 

for (int i = 0; i<3 ; ++i) 
    node->speed[i] = clamp(node->speed[i], pSystem->nVelocity, pSystem->velocity); 

사이드 노트 : "속도"와 "속도"의 의미를 전환 한 것처럼 보입니다.
속도는 벡터이며 방향과 크기가 있으며 속도는 속도의 크기 인 스칼라입니다.

관련 문제