[英]C Program Generates An odd output
最近,我嘗試開始學習C,並決定做一些項目Euler挑戰。 我寫了這段代碼來解決這個問題,但是當它運行時,它輸出的數字應該是不可能的。 我已經盡力解決了。 包括使我的一些積分變長,這些似乎都不起作用。 任何輸入都會很棒,謝謝!
#include <stdio.h>
int main(){
char num[] =
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450";
int inc;
long int next_biggest = 0;
for (inc = 0; inc <= 986; inc++){
int temp;
long int total = (int)num[inc];
for (temp = 1; temp <= 13; temp++){
total *= (int)num[(inc + temp)];
}
if ((total > next_biggest)){
next_biggest = total;
printf("Next Biggest Number: %ld\n", total);
}
}
}
線
long int total = (int)num[inc];
看起來像它將'3'
轉換為一個int
3,但沒有。 它的作用是將ASCII值'3'
分配給int
。
修復它,您的程序可以正常運行:)
long int total = num[inc] - '0';
本質上,這里發生的是我們獲得一個char
值(一個數字)並獲得其ASCII碼。 然后,基於以下事實:在ASCII中,所有數字都位於一個以'0'開頭的連續值塊中,我們計算出這些數字的面值並將其用作int
。
糾正上述行后,這是程序的輸出:
下一個最大數字:2032807552
下一個最大數字:2084481664
下一個最大號碼:2141716480
下一個最大編號:2144206848
您可以使用atoi(),atol()例如..將一個char或一個或多個char轉換為單個int或long類型。
http://www.cplusplus.com/reference/cstdlib/atoi/
您可以這樣操作,它將起作用:
#include <stdio.h>
#include <stdlib.h>
char buffer[256] = {"123456"};
char i = buffer[3];
printf("%d", atoi(&i) );
如此,我會這樣做:
int inc;
char convert;
long int next_biggest = 0;
for (inc = 0; inc <= 986; inc++){
int temp;
convert = num[inc];
long int total = atol(&convert);
for (temp = 1; temp <= 13; temp++){
convert = num[(inc + temp)];
total *= atol(&convert);
}
if ((total > next_biggest)){
next_biggest = total;
printf("Next Biggest Number: %ld\n", total);
}
}
所以基本的想法是..我還沒有測試,但是它應該像這樣工作。 長期使用ATOL。 請注意,您不需要很長的單個字符。 單個字符通常永遠不會超過255個無符號和128個有符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.