第一次發帖!!!大家好,所以我需要將一個數字乘以 10 的 (x) 冪,這取決于我可能需要的指數。我知道庫中有一個函式,<math.h>但我想知道是否可以讓我自己的函式實作基本相同,但僅用于10,而不是任何數字;這是一個課程作業,但由于我們沒有被告知這個庫,我想嘗試在沒有上述power()功能的情況下實作它。
這是我的代碼,它確實可以編譯,但我得到了一些奇怪的數字而不是預期的5000.
#include <cs50.h>
#include <stdio.h>
int ten_to_the(int n);
int main(void) {
int x = 50;
x *= ten_to_the(2);
printf("%.i\n", x);
}
int ten_to_the(int n) {
n = 1;
for (int i = 0; i < n; i ) {
n *= 10;
}
return n;
}
uj5u.com熱心網友回復:
因為你n在回圈的每次迭代中乘以 10,i < n永遠不會成為真的。在實踐中,n不斷變大,直到溢位并變為負數。
使用另一個變數來跟蹤結果,與您需要計算的迭代次數分開。
而不是這個:
int ten_to_the(int n)
{
n = 1;
for (int i = 0; i < n; i )
{
n *= 10;
}
return n;
}
這個:
int ten_to_the(int n)
{
int result = 1;
for (int i = 0; i < n; i )
{
result *= 10;
}
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520285.html
標籤:C
