2014-03-29 24 views
2

好的,所以起初,我非常習慣編程。這是我的學校作業,我不能使用轉換爲字符串。只是,如果,其他,因爲,而。指定的數字是什麼數字,其中有多少個數字?

在輸入上有數字和數字。

我知道如何獲取信息數字是指定的數字在一個數字,但我不知道如何找出有多少這些數字在那裏。

假設我的號碼是123 467(它必須小於999 999),我想要第三個號碼。我知道它大於100 000,所以我做數學 - (int)123 467/100 = 123,然後123%10 = 3.現在我需要知道數字中是否還有3個 - 但這裏是點 - 我不知道我應該使用什麼循環。

而且我還必須創建一些代碼來確定數字有多大(大於100/1000/10000/...)。

我不是要求一個完整的解決方案,但將不勝感激。即使是僞語言。

當前代碼(幾乎沒有):

double digit, number; 

try 
{ 
    digit = Convert.ToInt32(poledigit.Text); 
    number = Convert.ToInt32(polenumber.Text); 
} 
catch 
{ 
    MessageBox.Show("Zadejte číslo ve správném formátu"); 
    return; 
} 

if (digit > 6 & number > 999999) 
{ 
    MessageBox.Show("Číslo musí být menší než 999 999 a digit musí být menší než 6."); 
    return; 
} 

while(number >= 100000) 
{ 
    number /= Math.Pow(10, digit); 
    number %= 10; 
} 
+0

if(digit> 6&number> 999999)??如果兩個條件中的一個匹配,你不想返回嗎? –

+0

@AnthonyRaymond是的,我真的不確定什麼是沒有任何字符串返回的意義。我們正在學習C#2個月,所以我幾乎不知道我在做什麼。 –

+0

x)好的,你說過:如果數字> 6 AND數字> 999999,這意味着如果滿足兩個條件,您將輸入if if,但如果digit = 2且數字= 99999999999999 –

回答

1

您可以按如下方式遍歷數字:

int digitToSearch = 3; 
int count = 0; 
while (number != 0) 
{ 
    int digit = number % 10; 
    if (digit == digitToSearch) 
     count++; 
    number /= 10; 
} 
+0

我懷疑一個'Dictionary'的含義遠遠超過了他們迄今爲止的教導。 –

+0

謝謝!沒錯,我還沒有聽說過Dictionary。所以這可能無法用於我的作業。 –

+0

我已經更新了我的答案。請修改。 – Dmitry

2

我會創造一個int數組計算的位數

int[] digitCount = new int[10]; // Range: digitCount[0..9] 

然後確定通過消除最後一個數字一個接一個,直到該數字是零。這個循環重複下面的代碼:

int digit = number % 10; 
number /= 10; 
digitCount[digit]++; 

現在digitCount包含每個數字

int countOfDigit3 = digitCount[3]; 

如果您不能使用數組的計數,只計算所需的數字的出現次數

int digit = ...; 
int digitCount = 0; 

while (number != 0) { 
    int d = number % 10; 
    number /= 10; 
    if (d == digit) { 
     digitCount++; 
    } 
} 
+0

謝謝你的理解解決方案。但是我們不能使用我們還沒有在類中學過的東西(包括數組,函數等)。 –

+1

沒有字符串,數組或函數?你的老師是否曾經在我工作的地方編碼? –

+0

好吧,我的老師似乎正在學習如何與我們合作。我們的進度非常緩慢。我們將在2年內使用對象(當我18歲時)。 –

相關問題