C programming Question.

2008-11-16 12:41 am
5. Write a program which reads in an integer value between 2 and 10 as the
base of a number system, and then reads in a positive number written to that
base, and print its equivalent value in decimal number system.

Requirement: read in the second integer character by character using
getchar(); skip over any leading non-valid (i.e. not a digit between zero and
base-1) characters, then read valid characters until an invalid one is
encountered. Assume the length of the second integer is no longer than 10.

Test cases:
Input Output
========== ======
10 1234 1234
8 77 63
2 1111 15

回答 (2)

2008-11-16 12:40 pm
✔ 最佳答案
Here it is. (compiled using Dev C++) If you have questions, PM me.

#include <stdlib.h>
#include <stdio.h>
void baseN()
{
const int maxDigits=10;
int i,base=0;
long number;
char c, digits[maxDigits 1];
for(i=0;i<5;i ) // 5 tries
{
printf("Input base (2-10) : ");
scanf("%d",&base);
if(base>=2&&base<=10)break;
}
printf("number base = %d\n",base);
fflush(stdin);
printf("Input number (extraneous characters will terminate input): ");
number=0;
for(i=0;i<maxDigits;i )
{
c=getchar(); // get new character
if(c<'0'||c-'0'>=base)
{
digits[i]='\0'; // terminate string
break;
}
digits[i]=c; // concatenate digit to string
number=number*base (c-'0'); // shift left and add new digit
}
printf("Input number to base %d= %s\n", base, digits);
printf("Output number (decimal) = %ld\n",number);
}
int main()
{
baseN();
system("PAUSE");
return 0;
}
2008-11-16 3:43 am
1. 以scanf去讀取base數字輸入
2. 以scanf去讀取positive number的字串/char陣列
3. 檢查一下用家輸入的正整數是否符合base
4. 如檢查無誤, 以strlen找出正整數字串的長度, length
5. 把result置零
6. 以for廻圈, i 由 0 至 length - 1, 找出positive_number[i] * base ^ (length - i - 1), 並累積到result中.
7. 以printf顯示答案, base, positive_number, 及 result


收錄日期: 2021-04-13 16:14:25
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20081115000051KK01283

檢視 Wayback Machine 備份