[英]if statement doesn't work in the block of switch?
我編寫了一個簡單的函數,如下所示,但是它沒有按預期工作,在C ++中, if語句在switch塊中不起作用?
void any2ten(string origin, int type)
{
if(! (type == 2 || type == 8 || type == 16))
{
cout << "unsupport this " << endl;
return;
}
int result = 0;
for (int index = 0; index < origin.length(); index++)
{
int tmp = 0;
switch (origin[index])
{
if (type == 16)
{
case 'F':
case 'f':
tmp = 15 * pow(type, index); break;
case 'E':
case 'e':
tmp = 14 * pow(type, index); break;
case 'D':
case 'd':
tmp = 13 * pow(type, index); break;
case 'C':
case 'c':
tmp = 12 * pow(type, index); break;
case 'B':
case 'b':
tmp = 11 * pow(type, index); break;
case 'A':
case 'a':
tmp = 10 * pow(type, index); break;
case '9':
tmp = 9 * pow(type, index); break;
case '8':
tmp = 8 * pow(type, index); break;
}
if (type == 8 || type == 16)
{
case '7':
tmp = 7 * pow(type, index); break;
case '6':
tmp = 6 * pow(type, index); break;
case '5':
tmp = 5 * pow(type, index); break;
case '4':
tmp = 4 * pow(type, index); break;
case '3':
tmp = 3 * pow(type, index); break;
case '2':
tmp = 2 * pow(type, index); break;
}
case '1':
tmp = 1 * pow(type, index); break;
case '0':
tmp = 0; break;
default:
cout << "wrong character has got" << endl;
return;
break;
}
result += tmp;
}
cout << result << endl;
}
當我將函數測試為any2ten(“ aa”,8)時 ,結果為90而不是錯誤的character 。
有什么問題嗎?
if
語句在switch
塊中可以正常工作,您只需將其放在永遠不會執行的地方。 switch
語句跳轉到相應的case
,即其目的。 無論跳轉到什么地方,它都會跳過if
,因此if
永遠不會執行。
如果要添加代碼以使其能夠在switch
和if
之間跳轉,則if
將正常執行。 您可以使用任何類型的循環或goto
來執行此操作。
僅當沒有 case
匹配時才采用default
。 否則, switch
跳至匹配的case
。
switch
語句不能像您想象的那樣起作用。 它的行為方式不是用if
- else if
- else
替代,而是有所不同。
遇到switch
,過程將按照正確的case
跳轉到代碼。 這意味着您實際上完全跳過了放置在此處的if
的執行。
是的,它的確看起來很奇怪,因為您假設因為有了花括號,所以必須在if
條件的情況下執行if
否則就根本不需要輸入花括號,但是事實並非如此。
好吧,如果你的if語句的位置是沒有任何意義的。 switch語句跳轉到相應的情況,然后存在,因此不會執行if語句。 而且我不建議使用goto,因為這被認為是一種不好的做法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.