我的一个色值HEX码转化为rgb数值的代码,求完善。
本帖最后由 Tongxi 于 2012-12-5 10:30 编辑我写的代码如下:
#include <stdio.h>
/* hex to RGB */
main()
{
int r, g, b, c, pos;
pos = 1;
while(pos > 0){
scanf("%2x",&r);
scanf("%2x",&g);
scanf("%2x",&b);
printf("R:%d\nG:%d\nB:%d\n",r, g, b);
}
return 0;
}
起码有以下问题需要完善:
1.我想在输入xxoo后程序能停止(终止循环)。
2.在输入非色值HEX码(包含长度不对和字符错误的情况)后能提示重新输入
其它请大家补充完善^^ 自己回复给自己。只用《C程序设计语言》第一二章的内容
#include <stdio.h>
#define YES 1
#define NO 0
#define HEXL 2
#define FHEX 6
#define MAXWORD 1000
char s;
char c;
int err;
int htoi(char c);
int ten(int i);
main ()
{
int i, j;
int r, g, b;
err = YES;
for (i = 1; (s = getchar()) != EOF; ++i){
while (s == '\n'){
s = '\0';
--i;
if (i == FHEX){
i = 1;
r = ten(i);
i = i + HEXL;
g = ten(i);
i = i + HEXL;
b = ten(i);
if (err == NO){
printf("Forbidden character! Please resume load.\n");
err = YES;
break;
}
printf("R:%d,G:%d,B:%d\n", r, g, b);
}else{
printf("Input error! Please resume load.\n");
}
for ( ; i > 0; --i)
s = '\0';
break;
}
}
return 0;
}
/* htoi: convert hexadecimal string s to integer */
int htoi(char s[])
{
int hexdigit, i, inhex, n;
i = 0;
if (s == '0'){ /* skip optional 0x or 0X */
++i;
if (s == 'x' || s == 'X')
++i;
}
n = 0; /* integer value to be returned */
inhex = YES; /*assume valid hexadecimal digit*/
for (; inhex == YES; ++i){
if (s >= '0' && s <= '9')
hexdigit = s - '0';
else if (s >= 'a' && s <= 'f')
hexdigit = s - 'a' + 10;
else if (s >= 'A' && s <= 'F')
hexdigit = s - 'A' + 10;
else{
inhex = NO;/* not a valid hexadecimal digit */
if (i <= HEXL-1)
err = NO;
}
if (inhex == YES)
n = 16*n+hexdigit;
}
return n;
}
int ten(int i)
{
int j;
for (j = 0; j < HEXL; ++j){
c = s;
++i;
}
return htoi(c);
}
顶下帖子
页:
[1]