[英]Print integer as character digits (no arrays/printf/etc…)
我試圖在C語言中使用一些約束將整數打印到控制台,其中最重要的是,我只能按如下方式將單個字符寫入控制台:
void my_char(char ch)
}
write(1, &ch, 1);
}
其他約束包括沒有預定義的方法(printf,log等)。 沒有遞歸。 最后,我可能不會創建數組。
到目前為止,我想出了一種方法,可以很好地將數字打印出來...向后。
int main()
{
int i = -345320;
my_int(i);
return 0;
}
void my_int(int x)
{
char *a;
int n;
if(x < 0)
{
x = x * -1;
my_char('-');
}
while(x)
{
n = x % 10;
a = (char*)&n;
my_char(*a + 48);
x /= 10;
}
}
還有其他好的方法可以解決這個問題,或者我至少是朝着正確的方向前進嗎? 理想情況下,我想擴展它以在我提供的任何基數中打印整數,但是我需要從這里開始。
我在遍歷整數的每個字節上遍歷一個指針,但是我無法理解如何使用這些字符值來重新創建整數。
任何建議表示贊賞。 我寧願獲得一些見識,而不僅僅是代碼解決方案。 我也很喜歡使它變得更苗條的輸入。
這應該可以解決問題。 它輸出整數正向。
void my_int(int x)
{
int temp = 0;
int divFactor = 10;
if(x==0)
{
my_char('0');
return;
}
if(x < 0)
{
x = x * -1;
my_char('-');
}
temp = x;
while((temp /= 10) > 10) {divFactor *= 10;}
for(;divFactor > 0;divFactor /= 10)
{
temp = x;
temp /= divFactor;
my_char(temp + '0');
x -= divFactor * temp;
}
printf("\n done!");
}
int main()
{
int i = -1234001;
my_int(i);
return 0;
}
這是遵循您的約束的通用(難看!)解決方案。 它使用了我在上面的評論中給出的想法。 假定為32位整數。
void my_int(int x) {
int n = 1000000000;
if (x == 0) {
my_char('0');
return;
}
if (x == INT_MIN) { // INT_MIN is in limits.h
my_char('-'); my_char('2'); my_char('1');
my_char('4'); my_char('7'); my_char('4');
my_char('8'); my_char('3'); my_char('6');
my_char('4'); my_char('8');
return;
}
if (x < 0) {
x *= -1;
my_char('-');
}
while (n > x) n /= 10;
while (n != 0) {
my_char(x / n % 10 + '0');
n /= 10;
}
}
void my_int(int x)
{
int n;
int copy;
char digit;
// handle 0
if (!x)
{
my_char('0');
return;
}
// emit sign
if(x < 0)
{
x = x * -1;
my_char('-');
}
// count base-10 digits in x, store 10^n in n
n = 1;
copy = x/10; // shorten loop by 1 iteration
while (copy)
{
n *= 10;
copy /= 10;
}
// 'n' is now a digit selector
while (n)
{
digit = x/n;
my_char(digit + '0'); // print the most significant digit
x -= digit*n; // remove the most significant digit from x
n /= 10;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.