读书人

请问一个有关问题?这道题目如何编

发布时间: 2012-02-27 10:00:22 作者: rapoo

请教一个问题?这道题目怎么编?
题目:使用命令行参数编写一个程序,其功能是将任意一个正整数m变换为指定的n 进制数串输出。命令行的格式为:
chang m n

[解决办法]
函数名: itoa
功 能: 把一整数转换为字符串
用 法: char *itoa(int value, char *string, int radix);
程序例:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 12345;
char string[25];

itoa(number, string, 10);
printf( "integer = %d string = %s\n ", number, string);
return 0;
}


[解决办法]
char base[]= "0123456789abcdefghijklmnopqrstuvwxyz " /* 可支持任意低于36进制数串输出 */

int main(int argc, int **argv)
{

if(argc !=3)
fprintf(stderr, "format input error usage: <chang m n> \n ");
............

}
[解决办法]
#include "stdio.h "
change(int m,int n)
{
int *d=new int[m],len=0;;
while(m)
{
d[len++]=m%n;
m/=n;
}
for(int i=0;i <len;i++)
printf( "%d ",d[len-i-1]);
delete []d;
}
void main()
{
int m=16,n=8;//八进制
change(m,n);
}
[解决办法]
命令行格式应该是从cmd下面进入程序进行调用

cmd -> 进入程序的.exe目录 -> 调用
[解决办法]
楼上正解,我做个译手吧!
int main(void)
{
int number = 12345;
char string[25]; /*定义一维数组,并定义其长度(自定义)*/

itoa(number, string, 10);/*使用itoa函数,进行换算*/
printf( "integer = %d string = %s\n ", number, string); /*输出结果*/
return 0;
}

[解决办法]
//file change.cpp

#include <iostream>
#include <vector>

using namespace std;

bool CheckInput(int argc, char**& argv);

int main(int argc, char** argv)
{

if (!CheckInput(argc, argv)) return 1;

long m = atol(argv[1]);
long n = atol(argv[2]);


vector <int> changedValue;

int dividend = m;
int divisor = n;
int quotient = dividend/divisor;
int remainder = dividend%divisor;
changedValue.push_back(remainder);
while (quotient> 0) {
dividend = (dividend - remainder) / divisor;
quotient = dividend / divisor;
remainder = dividend % divisor;
changedValue.push_back(remainder);
}

//output the value
for(int i=changedValue.size()-1; i> =0; --i) {
cout < <changedValue[i];
if (i> 0) cout < < "_ ";
}
cout < <endl;
}

bool CheckInput(int argc, char**& argv)
{
if (argc <3) {
cout < < "Usage Error! " < <endl;
cout < < "Usage: change m n " < <endl;
cout < < " m: the int number to convert! " < <endl;
cout < < " n: the base convertion to! " < <endl;
return false;
}

if (atol(argv[2]) <=1) {
cout < < "ERROR: invalid base: " < <argv[2] < <endl;
return false;
}
if (atol(argv[1]) <0) {
cout < < "ERROR: invalid integer: " < <argv[1] < <endl;


return false;
}

//adding other error checking here
//for example the maximum int value can be represent......

return true;
}

// here is the following execution example
// change 1024 2
// 1_0_0_0_0_0_0_0_0_0_0
//
// change 1024 16
// 4_0_0
//
// change 1000 25
// 1_15_0
//
// change 1000 500
// 2_0
//
// change 1000 2000
// 1000
[解决办法]
用栈来做
这是一个栈的头文件
/*stack.h*/
#ifndef STACK_H
#define STACK_H
typedef struct N
{
int data;
char Ch;
struct N *next;
} NODE;

class STACK
{
private:
NODE *Top,*Bottom;
int M_Size;
public:
STACK();
STACK(int Max);
int Empty();
void Push(char c);
char Pop();
char const GetTop();
void Clear();
int const CurrentSize();
~STACK();
};
#endif

读书人网 >C语言

热点推荐