// MATHS
S = sent / words *100;
// ^^^^^^^^^^^^^^^^^ when tested S = 0.00000 no matter what.
L = letters / words * 100;
int get_sent(string text) {
int sent = 0;
for (int i = 0, len = strlen(text); i < len; i ) {
if (text[i] == 46 || text[i] == 33 || text[i] == 63) {
sent ;
}
}
return sent;
}
S = 0.000無論輸入什么,都可以測驗我的代碼。return sent 回傳正確數量的句子,但是當我這樣做時S = sent / words *100;,它似乎沒有使用 return 正確加載發送。我已經把臉撞在鍵盤上一個小時試圖找出原因。除此之外,我已經完成了。
uj5u.com熱心網友回復:
在您的代碼中
S = sent / words * 100;
將執行整數運算,因為所有涉及的運算元都是int. 如果您需要浮點運算,則需要強制執行它。就像是
S = sent / (float) words * 100;
其他陳述也是如此。
uj5u.com熱心網友回復:
S對于初學者來說,不需要L在檔案范圍內宣告變數
//preload variables.
float S, L;
一般來說,這是一個壞主意。在使用它們的最小范圍內宣告變數。所以你應該宣告變數S并L在main.
您兩次宣告該函式get_words。
int get_sent(string text);
int get_words(string text);
int get_letter(string text);
int get_words(string text);
盡管它不會產生編譯器錯誤,但它可能會使代碼的讀者感到困惑。所以洗掉一個宣告。
該函式strlen具有回傳型別size_t。一般來說,有符號型別int不足以存盤字串的長度。所以你的函式應該有無符號型別size_t作為回傳型別。
size_t get_sent(string text);
size_t get_words(string text);
size_t get_letters(string text);
在函式的回圈內呼叫函式strlen是多余的和低效的。
例如get_letter,應該重命名為get_letters類似于名稱的函式get_words可以如下所示
size_t get_letters(string text)
{
size_t letters = 0;
// count the letter in the string from user and count
// only upper and lowercase letters all = 1 "point" per letter.
for ( ; *text != '\0'; text )
{
//count the letters a-z && A-Z.
if ( isalpha( ( unsigned char )*text ) )
{
//add a "point" to letter.
letters ;
}
}
//return "points" back to main.
return letters;
}
在 main 函式中呼叫如下
size_t letters = get_letters(text);
要輸出值,您需要使用轉換規范%zu而不是%i.
//print how many letters were typed back to user, // this after testing.
printf("%zu Letters\n", letters);
相應地,變數 words 和 sent 也應該宣告為具有型別size_t
//get the number of words within text.
size_t words = get_words(text);
//get the number of sentences within the text.
size_t sent = get_sent(text);
并且您需要使用轉換規范%zu而不是%i輸出它們。
//print how many words were typed back to user, // this after testing.
printf("%zu Words\n", words);
//print how many sentences were typed back to user, // this after testing.
printf("%zu Sentences\n", sent);
函式get_words不正確。它不計算字數。它計算空格。例如,如果字串text包含相鄰的空格,則函式回傳不正確的值。
該函式可以通過以下方式定義
size_t get_words( string text )
{
size_t words = o;
while ( *text != '\0' )
{
while ( isspace( ( unsigned char )*text ) ) text;
if ( *text != '\0' )
{
words;
while ( *text && !isspace( ( unsigned char )*text ) ) text;
}
}
return words;
}
該函式get_sent也應該重寫。至少在這個宣告中使用幻數是一個壞主意
if (text[i] == 46 || text[i] == 33 || text[i] == 63 )
因為它使代碼不清楚且不可讀。
至于您的問題,那么您使用的是整數算術而不是浮點算術,例如
S = sent / words * 100;
L = letters / words * 100;
你應該寫
S = ( float )sent / words * 100;
L = ( float )letters / words * 100;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515929.html
