- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我试图开发一个C程序,通过输入电阻上标记的色带来计算电阻值。
忽略电阻公差。
例如
Enter the colours of the resistor’s three bands, beginning
with the band nearest the end. Type the colours in lowercase
letters only, NO CAPS
Band 1 => green
Band 2 => black
Band 3 => yellow
Resistance value: 500 000 -ohms
Do you want to decode another resistor (Y/N)?
=> Y
Invalid colour: vilet
仅在此处
Invalid colours: pink, silver
这里有两种无效颜色“粉色”和
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// resister bands
enum resistor_band_items {BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE, UNKNOWN};
struct items
{
char *name;
enum resistor_band_items id;
} item_list[] = {
{"black", BLACK},
{"brown", BROWN},
{"red", RED},
{"orange", ORANGE},
{"yellow", YELLOW},
{"green", GREEN},
{"blue", BLUE},
{"violet", VIOLET},
{"gray", GRAY},
{"white", WHITE}
};
char answer[10], status[1] = "Y"; //answer => user input
char bands[3][10]; //string for resistor bands
//variables to hold the band values
int colour[3];
//function prototype
int inputVal (int *a, char b[3][10]);
double calResistance (int a, int b, int c);
void print_number (double number);
int main(void)
{
int i, invalid; //counter
double resistor_value; //total resistance value
enum resistor_band_items mid;
struct items *choice = NULL;
while (strcmp(status, "Y") == 0)
{
//print the question to the user
printf("Enter the colours of the resistor's three bands,\nbeginning with the band nearest to the end.\nType the coloues in lowercase letters only, NO CAPS.\n");
for (int j = 0; j<3; j++)
{
printf("Band %d => ", j + 1);
gets(answer);
for (i = 0, choice = NULL; i < sizeof item_list/sizeof(struct items); ++i)
{
if (strcmp(answer, item_list[i].name) == 0)
{
choice = item_list + i;
break;
}
}
mid = choice ? choice ->id : UNKNOWN;
colour[j] = mid;
strcpy(bands[j], answer);
}
invalid = inputVal (colour, bands);
if (invalid == 0)
{
//calculate resistor value
resistor_value = calResistance(colour[0], colour[1],colour[2]);
// print resistor value to user
printf("%.0f\n", resistor_value);
print_number(resistor_value);
}
printf("Do you want to decode another resistor (Y/N)?\n");
gets(status);
if (strcmp(status, "Y") == 0);
else break;
}
return 0;
}
int inputVal (int *a, char b[3][10])
{
int counter = 0, index[3];
for (int i = 0; i < 3; ++i)
{
if (a[i] == 10)
{
index[i] = i;
//printf("%s%s", b[i], " ");
counter++;
}
}
if (counter == 0)
{
return 0;
}
else if (counter == 1)
{
printf("Invalid colour: %s\n", b[index[0]]);
}
else if (counter == 2)
{
printf("Invalid colours:");
printf(" %s", b[index[0]]);
printf(",");
printf(" %s\n", b[index[1]]);
}
else
{
printf("Invalid colours:");
printf(" %s", b[index[0]]);
printf(",");
printf(" %s", b[index[1]]);
printf(",");
printf(" %s\n", b[index[2]]);
}
return 1;
}
double calResistance (int a, int b, int c)
{
double results;
unsigned power = 10;
while (b >= power)
{
power *= 10;
}
results = a * power + b;
results = results * pow(10, c);
return results;
}
void print_number (double number)
{
double n = number, *x;
int c = 0;
int j = 1;
while (n != 0 && n > 1)
{
n /= 10.0;
c += 1;
}
x = malloc (c * sizeof(double));
printf("%d\n", c);
for (int i = 0; i <= c; i++)
{
double digit = fmod (number, 10.0);
x[i] = digit;
number /= 10.0;
}
printf("Resistance value: \n\n");
for (int i = c - 1; i >= 0; i--)
{
printf("#%d = %.0f\n",i, x[i]);
}
printf("\n\n\n");
for (int i = c - 1; i >= 0; i--)
{
if (j == 3 || j == 7 || j == 11 || j == 15)
{
printf(" ");
}
else
{
printf("%.0f", x[i]);
}
j++;
}
printf(" -ohms\n");
//free(x);
}
void print_number (double number)
{
double n = number, *x;
int c = 0;
int j = 1;
while (n != 0 && n > 1)
{
n /= 10.0;
c += 1;
}
x = malloc (c * sizeof(double));
printf("c = %d\n", c);
for (int i = 0; i < c; i++)
{
double digit = fmod (number, 10.0);
x[i] = digit;
number /= 10.0;
}
printf("Resistance value: \n");
for (int i = c; i >= 0; i--)
{
printf("#%d = %.0f\n",i, x[i]);
}
printf("\n\n");
printf("remainder of c = %d\n\n",c%3);
if (c % 3 == 2)
{
for (int i = c; i >= 0; i--)
{
if (j == 4 || j == 7 || j == 11 || j == 15)
{
printf(" ");
i++;
}
else
{
printf("%.0f", x[i]);
}
j++;
}
printf(" -ohms\n");
}
else
{
for (int i = c - 1 ; i >= 0; i--)
{
//printf("%.0f", x[i]);
if (c % 3 == 0)
{
if (j == 4 || j == 8 || j == 12 || j == 16)
{
printf(" ");
i++;
}
else
{
printf("%.0f", x[i]);
}
}
else if (c % 3 == 1)
{
if (j == 2 || j == 6 || j == 10 || j == 14)
{
printf(" ");
i++;
}
else
{
printf("%.0f", x[i]);
}
}
j++;
}
printf(" -ohms\n");
//free(x);
}
}
argc
和
argv
的原因是客户端有一个需要遵循的受限格式(这让我很生气!)
//importing required header files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// resister bands
enum resistor_band_items {BLACK, BROWN, RED, ORANGE, YELLOW, GREEN,
BLUE, VIOLET, GRAY, WHITE, UNKNOWN};
//constants for min/max colour arguments and max colour char
enum {MINC = 3, MAXC = 4, MAXCC = 8};
struct items
{
char *name;
enum resistor_band_items id;
} item_list[] = {
{"black", BLACK},
{"brown", BROWN},
{"red", RED},
{"orange", ORANGE},
{"yellow", YELLOW},
{"green", GREEN},
{"blue", BLUE},
{"violet", VIOLET},
{"gray", GRAY},
{"white", WHITE}
};
//resistor multiplier values
int multiplier[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000};
char answer[3][10]; // User input
int colour_val[3]; //stores the band value
#define nItems (sizeof item_list/sizeof *item_list)
//function prototyps
int srchItems (char *ccode); //a search for index values
char *strcpy2lower (char *dest, char *src); //converts to lower case
int scmp (char *a, char *b); //simple string comarison
char *sepnumber (char *s, long val);
int invalid (char answer[3][10]);
//main function
int main(int argc, char const *argv[])
{
int i; // counter
char status = 'Y';// Keeps the program running when user inputs 'Y'
long resistor_value = 0; //Total resistance
int r, err, mult; //holds the significant figure, Error, Multiplier
char resistor_value_string[20] = "";//formatted output
while (status == 'Y') //The program runs under this
{
//print the question to the user
printf("Enter the colours of the resistor's three bands,\nbeginning with the band nearest to the end.\nType the coloues in lowercase letters only, NO CAPS.\n");
for (i = 0; i < MINC; ++i)
{
printf("Band %d => ", i + 1); // print headers for each band
scanf(" %s", &answer[i]); // get the user input
}
for (i = 0; i < MINC - 1; ++i) //converts colours into index
{
if ((r = srchItems (answer[i])) > -1)
{
// from significant figure
resistor_value = (resistor_value * 10) + r;
}
else
{
invalid(answer);
err = 2;
}
}
if (err > 1)
{
printf("Do you want to decode anothe resistor (Y/N)?\n");
scanf (" %c", &status);
if (status == 'Y');
else break;
}
else
{
mult = srchItems (answer[i]); // get multiplier index
resistor_value *= multiplier[mult]; // Calculate final value
sepnumber (resistor_value_string, resistor_value);
printf("Resistor value: ");
/*for (int i = 0; i < (strlen(resistor_value_string) ); ++i)
{
printf("%c", resistor_value_string[i]);
}
*/
puts (resistor_value_string);
//printf(" -ohm\n");
//memset (resistor_value_string, 0, 50);
printf("Do you want to decode anothe resistor (Y/N)?\n");
scanf (" %c", &status);
if (status == 'Y');
else break;
/*Debug
for (int i = 0; i < MINC; ++i)
{
printf("item_list[%d] = %s\n", i, answer[i]);
}
printf("Total resistance = %ld\n", resistor_value);
//end of debug */
}
}
return 0;
}
int srchItems (char *ccode)
{
int i;
char lccode [MAXCC] = "";
strcpy2lower (lccode, ccode); // converts everything to lower case
for (int i = 0; i < (int)nItems; ++i)
if (*lccode == *(item_list[i].name))
if (!scmp(item_list[i].name, lccode))
return i;
return -1;
}
char *strcpy2lower (char *dest, char *src)
{
if (!src || !dest) return NULL;
char *d = dest;
for (; *src; src++, d++)
if ('A' <= *src && *src <= 'Z')
*d = *src | (1 << 5);
else
*d = *src;
*d = 0;
return dest;
}
int scmp (char *a, char *b)
{
if (!a && !b) return 0;
if ( a && !b) return 1;
if (!a && b) return -1;
for (; *a && *b && *a == *b; a++, b++) {}
return *a - *b;
}
/** separate long value every 3rd char into 's' */
char *sepnumber (char *s, long val)
{
char numstr[3 * MAXCC] = "";
char *p = numstr;
size_t idx = 0, len = 0;
sprintf (numstr, "%ld", val);
for (; *p; p++) {}
len = p - numstr;
p = s + 3 * MAXCC - 2;
while (len--) {
if (idx++ == 3) {
idx = 1;
*p-- = ' ';
}
*p = numstr[len];
if (len) p--;
}
for (idx = 0; *p; p++, idx++) s[idx] = *p; /* copy to s */
s[idx] = *p; /* nul-terminate */
return s;
}
int invalid (char answer[3][10])
{
int r, counter = 0, incorrect[3], i;
for (i = 0; i < MINC; ++i)
{
if ((r = srchItems (answer[i])) == -1)
{
incorrect[i] = r;
counter++;
}
}
if (counter == 1)
{
printf("%s","Invalid colour: " );
printf("%s ", answer[i]);
printf("\n");
}
i = 0;
}
$ ./RQ1.exe
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the coloues in lowercase letters only, NO CAPS.
Band 1 => red
Band 2 => orange
Band 3 => green
Resistor value: 2 300 000
Do you want to decode anothe resistor (Y/N)?
Y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the coloues in lowercase letters only, NO CAPS.
Band 1 => green
Band 2 => black
Band 3 => yellow
Resistor value: -2 101 970 656
Do you want to decode anothe resistor (Y/N)?
Y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the coloues in lowercase letters only, NO CAPS.
Band 1 => read
Band 2 => gren
Band 3 => blu
Do you want to decode anothe resistor (Y/N)?
Y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the coloues in lowercase letters only, NO CAPS.
Band 1 => red
Band 2 => orange
Band 3 => green
Do you want to decode anothe resistor (Y/N)?
N
#include <stdio.h>
#include <string.h>
#define nItems (sizeof item_list/sizeof *item_list)
char status = 'Y';
//
enum {MINC = 3, MAXCC = 10};
// resister bands
enum resistor_band_items {BLACK, BROWN, RED, ORANGE, YELLOW, GREEN,
BLUE, VIOLET, GRAY, WHITE, UNKNOWN};
struct items
{
char *name;
enum resistor_band_items id;
} item_list[] = {
{"black", BLACK},
{"brown", BROWN},
{"red", RED},
{"orange", ORANGE},
{"yellow", YELLOW},
{"green", GREEN},
{"blue", BLUE},
{"violet", VIOLET},
{"gray", GRAY},
{"white", WHITE}
};
unsigned int multiplier[] = {1, 10, 100, 1000, 10000, 100000, 1000000,
10000000, 100000000, 1000000000};
int srchItems (char *ccode); //a search for index values
char *strcpy2lower (char *dest, char *src); //converts to lower case
int scmp (char *a, char *b); //simple string comarison
char *sepnumber (char *s, long val); //puts space every 3rd digit
int main(void)
{
int i, error = 0, mult;
char input[MINC][MAXCC]; //user input
char invalid[MINC][MAXCC]; // invalid enteries
int colour_val[MINC]; //stores the band value
long total_resistance = 0;
char resistor_value_string[20] = "";//formatted output
do
{
//prompt user
printf("%s\n%s\n%s\n",
"Enter the colours of the resistor's three bands,",
"beginning with the band nearest to the end.",
"Type the colours in lowercase letters only, NO CAPS.");
for (i = 0; i < MINC; ++i)
{
printf("Band %d => ", i + 1); // print headers for each band
scanf(" %s", &input[i]); // get the user input
// converts user input to index of colours
colour_val[i] = srchItems(input[i]);
}
for (i = 0; i < MINC; ++i)
{
if (colour_val[i] == -1)
{
strcpy(invalid[i], input[i]);
error++;
}
}
if (error > 0)
{
if (error == 1)
{
printf("Invalid colour: %s\n", invalid[0]);
}
else if (error == 2)
{
printf("Invalid colours: %s, %s\n", invalid[0], invalid[1]);
}
else
{
printf("Invalid colours: %s, %s, %s\n",
invalid[0], invalid[1], invalid[2]);
}
}
else
{
//
for (i = 0; i < MINC - 1; ++i)
{
total_resistance = (total_resistance * 10) + colour_val[i];
}
mult = colour_val[2];
total_resistance *= multiplier[mult];
sepnumber (resistor_value_string, total_resistance);
printf("Resistance value: %s -Ohms\n", resistor_value_string);
//debug
for (i = 0; i < MINC; ++i)
{
//printf("Input ==> %s\t", input[i]);
//printf("index ==> %d\n", colour_val[i]);
}
//end debug
}
error = 0;
total_resistance = 0;
for (i = 0; i < MINC; ++i)
{
colour_val[i] = 0;
}
//ask user if they want to continue
printf("Do you want to decode another resistor?\n");
scanf(" %c", &status);
if (status == 'Y');
else break;
} while (status == 'Y');
return 0;
}
int srchItems (char *ccode)
{
int i;
char lccode [MAXCC] = "";
strcpy2lower (lccode, ccode); // converts everything to lower case
for (int i = 0; i < (int)nItems; ++i)
if (*lccode == *(item_list[i].name))
if (!scmp(item_list[i].name, lccode))
return i;
return -1;
}
char *strcpy2lower (char *dest, char *src)
{
if (!src || !dest) return NULL;
char *d = dest;
for (; *src; src++, d++)
if ('A' <= *src && *src <= 'Z')
*d = *src | (1 << 5);
else
*d = *src;
*d = 0;
return dest;
}
int scmp (char *a, char *b)
{
if (!a && !b) return 0;
if ( a && !b) return 1;
if (!a && b) return -1;
for (; *a && *b && *a == *b; a++, b++) {}
return *a - *b;
}
/** separate long value every 3rd char into 's' */
char *sepnumber (char *s, long val)
{
char numstr[3 * MAXCC] = "";
char *p = numstr;
size_t idx = 0, len = 0;
sprintf (numstr, "%ld", val);
for (; *p; p++) {}
len = p - numstr;
//printf("%d\n", len);
p = s + 3 * MAXCC - 2;
while (len--) {
if (idx++ == 3) {
idx = 1;
*p-- = ' ';
}
*p = numstr[len];
if (len) p--;
}
for (idx = 0; *p; p++, idx++) s[idx] = *p; /* copy to s */
s[idx] = *p; /* nul-terminate */
return s;
}
$ ./Q1_token.exe
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the colours in lowercase letters only, NO CAPS.
Band 1 => green
Band 2 => black
Band 3 => yellow
Resistance value: 500 000 -Ohms
Do you want to decode another resistor?
Y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the colours in lowercase letters only, NO CAPS.
Band 1 => red
Band 2 => orange
Band 3 => green
Resistance value: 2 300 000 -Ohms
Do you want to decode another resistor?
Y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the coloues in lowercase letters only, NO CAPS.
Band 1 => pink
Band 2 => silver
Band 3 => red
Invalid colours: pink, silver
Do you want to decode another resistor?
Y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Type the colours in lowercase letters only, NO CAPS.
Band 1 => vilot
Band 2 => brown
Band 3 => read
Invalid colours: vilot, silver
Do you want to decode another resistor?
N
最佳答案
确定电阻值有效数字的代码比需要的要复杂得多。由于您声明了structitem_list
的全局数组,所以要形成有效数字,只需使用item_list
作为查找表来查找输入的色带的索引。对于随后的每种颜色(第二种颜色[第三种颜色为5波段]),只需在添加索引之前将当前电阻值乘以10
。
例如,使用索引变量item_list
和电阻值r
(包括检查是否存在无效颜色),代码可以减少为:
int multiplier[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 };
...
int err = 0, i, mult, r;
long rval = 0;
printf ("\ncolor bands determining significant figures:\n\n");
for (i = 1; i < argc - 1; i++) { /* convert colors to index */
if ((r = srchitems (argv[i])) != -1) {
rval = rval * 10 + r; /* form significant figure */
prnitem (r);
}
else {
fprintf (stderr, "error: invalid color '%s'\n", argv[i]);
err = 1;
}
}
if (err) return 1;
mult = srchitems (argv[i]); /* get multiplier index */
rval *= multiplier[mult]; /* calculare final value */
printf ("\nmultiplier:\n\n");
prnitem (mult);
printf ("\nresistor value : %ld -ohms\n\n", rval);
return 0;
rval
函数只返回给定颜色的
srchitems
中的索引(作为程序的参数输入,例如
item_list
,
argv[1]
,…),您可以编写一个简单的
argv[2]
,在执行查找之前将所有输入转换为小写:
/** search item_list for color code 'ccode', return index
* returns array index on success, -1 otherwise.
*/
int srchitems (char *ccode)
{
int i;
char lccode[MAXCC] = ""; /* array to hold lowercase color */
strcpy2lower (lccode, ccode); /* convert string to lowercase */
for (i = 0; i < (int)nitems; i++) /* lookup index */
if (*lccode == *(item_list[i].name))
if (!scmp (item_list[i].name, lccode))
return i;
return -1; /* return -1 on error */
}
srchitems
替换为
scmp
(包括
strcmp
)如果有任何问题,请告诉我。
#include <stdio.h>
/* resister bands */
enum resistor_band_items { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN,
BLUE, VIOLET, GRAY, WHITE, UNKNOWN };
/* constants for min/max color arguments and max color chars */
enum { MINC = 3, MAXC = 4, MAXCC = 8 };
struct items /* could be simple array of strings */
{
char *name;
enum resistor_band_items id;
} item_list[] = {
{"black", BLACK},
{"brown", BROWN},
{"red", RED},
{"orange", ORANGE},
{"yellow", YELLOW},
{"green", GREEN},
{"blue", BLUE},
{"violet", VIOLET},
{"gray", GRAY},
{"white", WHITE}
};
/* resistor multiplier values */
int multiplier[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 };
#define nitems (sizeof item_list/sizeof *item_list)
int srchitems (char *ccode);
char *strcpy2lower (char *dest, char *src);
int scmp (char *a, char *b);
void prnitem (int i);
int main (int argc, char **argv) {
if (argc < MAXC || MAXC + 1 < argc) { /* check 3 or 4 arguments */
fprintf (stderr, "error: invalid input, usage: %s c1 c2 c3 [c4]\n"
"usage: enter color codes for 4 or 5-band resistor\n"
" (tolerance ignored, enter 4 colors max)\n",
argv[0]);
return 1;
}
int err = 0, i, mult, r;
long rval = 0;
printf ("\ncolor bands determining significant figures:\n\n");
for (i = 1; i < argc - 1; i++) { /* convert colors to index */
if ((r = srchitems (argv[i])) != -1) {
rval = rval * 10 + r; /* form significant figure */
prnitem (r);
}
else {
fprintf (stderr, "error: invalid color '%s'\n", argv[i]);
err = 1;
}
}
if (err) return 1;
mult = srchitems (argv[i]); /* get multiplier index */
rval *= multiplier[mult]; /* calculare final value */
printf ("\nmultiplier:\n\n");
prnitem (mult);
printf ("\nresistor value : %ld -ohms\n\n", rval);
return 0;
}
/** search item_list for color code 'ccode', return index
* returns array index on success, -1 otherwise.
*/
int srchitems (char *ccode)
{
int i;
char lccode[MAXCC] = "";
strcpy2lower (lccode, ccode);
for (i = 0; i < (int)nitems; i++)
if (*lccode == *(item_list[i].name))
if (!scmp (item_list[i].name, lccode))
return i;
return -1;
}
/** copy and convert string to lowercase.
* returns copy of string with all chars converted to lowercase.
* ('dest' must be of sufficient size of hold 'src')
*/
char *strcpy2lower (char *dest, char *src)
{
if (!src || !dest) return NULL;
char *d = dest;
for (; *src; src++, d++)
if ('A' <= *src && *src <= 'Z')
*d = *src | (1 << 5);
else
*d = *src;
*d = 0;
return dest;
}
/** simple string comparison (like strcmp) */
int scmp (char *a, char *b)
{
if (!a && !b) return 0;
if ( a && !b) return 1;
if (!a && b) return -1;
for (; *a && *b && *a == *b; a++, b++) {}
return *a - *b;
}
void prnitem (int i)
{
printf (" item_list[%d] name: %-6s id: %d\n",
i, item_list[i].name, item_list[i].id);
}
$ ./bin/resistor green blue yellow
color bands determining significant figures:
item_list[5] name: green id: 5
item_list[6] name: blue id: 6
multiplier:
item_list[4] name: yellow id: 4
resistor value : 560000 -ohms
$ ./bin/resistor Red Orange Violet Black
color bands determining significant figures:
item_list[2] name: red id: 2
item_list[3] name: orange id: 3
item_list[7] name: violet id: 7
multiplier:
item_list[0] name: black id: 0
resistor value : 237 -ohms
$ ./bin/resistor pink silver green
color bands determining significant figures:
error: invalid color 'pink'
error: invalid color 'silver'
string.h
转换为字符串(不带小数点),然后从末尾将字符复制到新字符串并每3个字符添加一个
number
呢?这不是一个相当复杂的方法,您依赖于数值计算来测试/分离您的数字?这让事情变得简单多了。(即使您使用
space
是出于一些前所未闻的原因——假设您最终会合并容忍度),但这种方法确实没有什么区别。请尝试以下操作:
void print_number (double number)
{
char numstr[3 * MAXCC] = "", sepstr[3 * MAXCC] = "";
char *p = NULL;
size_t idx = 0, len = 0;
sprintf (numstr, "%.0lf", number); /* write double to string */
len = strlen (numstr); /* get length */
p = sepstr + 3 * MAXCC - 2; /* set p at last char in sepstr */
while (len--) { /* for each char in numstr */
if (idx++ == 3) { /* if 3 characters copied */
idx = 1; /* reset index */
*p-- = ' '; /* write a space in sepstr */
}
*p = numstr[len]; /* write char in sepstr */
if (len) p--; /* decrement p if not at 0 */
}
printf ("p : '%s'\n", p); /* print the separate value */
}
double
中,您可以简单地将字符数组传递给
print_number
并将
p
复制到数组中(在这种情况下,您甚至可以更改
main
以返回
print_number
。)让我知道它是否有效。如果你不能那样做,那么我将研究你的数字逻辑,但那需要阿司匹林,而且可能在早上
char *
:)
输出
5 => '5'
55 => '55'
555 => '555'
5555 => '5 555'
55555 => '55 555'
555555 => '555 555'
5555555 => '5 555 555'
55555555 => '55 555 555'
555555555 => '555 555 555'
print_number
声明/初始化移到
sepstr
中,然后将其作为数组传递给您的
main
(下面的my
print_number
)。
char *sepnumber (char *s, long val);
...
long rval = 0;
char rstr[3 * MAXCC] = "";
...
printf ("\nresistor value : %s -ohms\n\n", sepnumber (rstr, rval));
return 0;
}
...
/** separate long value every 3rd char into 's' */
char *sepnumber (char *s, long val)
{
char numstr[3 * MAXCC] = "";
char *p = numstr;
size_t idx = 0, len = 0;
sprintf (numstr, "%ld", val);
for (; *p; p++) {}
len = p - numstr;
p = s + 3 * MAXCC - 2;
while (len--) {
if (idx++ == 3) {
idx = 1;
*p-- = ' ';
}
*p = numstr[len];
if (len) p--;
}
for (idx = 0; *p; p++, idx++) s[idx] = *p; /* copy to s */
s[idx] = *p; /* nul-terminate */
return s;
}
$ ./bin/resistor green blue yellow
color bands determining significant figures:
item_list[5] name: green id: 5
item_list[6] name: blue id: 6
multiplier:
item_list[4] name: yellow id: 4
resistor value : 560 000 -ohms
$ ./bin/resistor Red Orange Violet Brown
color bands determining significant figures:
item_list[2] name: red id: 2
item_list[3] name: orange id: 3
item_list[7] name: violet id: 7
multiplier:
item_list[1] name: brown id: 1
resistor value : 2 370 -ohms
sepnumber
(您的
rval = 0;
)。始终检查哪些值可能是累加值等,并记住在每个循环开始时重置这些值。在大多数情况下处理此问题的另一种方法是在循环范围内声明变量,以便在每次迭代时自动重新初始化它们。
resistor_value
应该类似于以下内容:
int main (void) {
for (;;) { /* loop for input */
int err = 0, i, mult, r; /* variables have block scope only */
long rval = 0;
char ccode[MAXCC] = "", rstr[3 * MAXCC] = "";
printf ("\nEnter the colours of the resistor's three bands,\n"
"beginning with the band nearest to the end.\n");
for (i = 0; i < MINC; i++) { /* convert colors to index */
printf ("Band %d => ", i + 1);
if (scanf (" %7s", ccode) != 1) {
fprintf (stderr, "error: invalid input or EOF.\n");
return 1;
}
if ((r = srchitems (ccode)) != -1) {
if (i < 2) {
rval = rval * 10 + r; /* form significant figure */
}
else {
mult = srchitems (ccode); /* get multiplier index */
rval *= multiplier[mult]; /* calculare final value */
}
}
else {
fprintf (stderr, "error: invalid color '%s'\n", ccode);
err = 1;
}
}
if (err) return 1;
printf ("Resistor value : %s -ohms\n", sepnumber (rstr, rval));
printf ("\nDo you want to decode another resistor (y/n)? ");
if (scanf (" %7s", ccode) != 1) {
fprintf (stderr, "error: invalid input or EOF.\n");
return 1;
}
if (*ccode != 'y' && *ccode != 'Y') break;
}
return 0;
}
$ ./bin/resistor2
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Band 1 => green
Band 2 => blue
Band 3 => yellow
Resistor value : 560 000 -ohms
Do you want to decode another resistor (y/n)? y
Enter the colours of the resistor's three bands,
beginning with the band nearest to the end.
Band 1 => red
Band 2 => orange
Band 3 => orange
Resistor value : 23 000 -ohms
Do you want to decode another resistor (y/n)? n
关于c - 以色带为输入计算电阻值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019527/
SQL 和一般开发的新手,我有一个表(COUNTRIES),其中包含字段(INDEX、NAME、POPULATION、AREA) 通常我添加一个客户端(Delphi)计算字段(DENSITY)和 On
我想使用 calc(100%-100px),但在我的 demo 中不起作用由于高度只接受像素,因此如何将此百分比值转换为像素。 最佳答案 以下将为您提供高度: $(window).height();
我正在尝试在 MySQL 中添加列并动态填充其他列。 例如我有一张表“数字”并具有第 1 列、第 2 列、第 3 列,这些总数应填充在第 4 列中 最佳答案 除非我误解了你的问题,否则你不只是在寻找:
我想返回简单计算的结果,但我不确定如何执行此操作。我的表格如下: SELECT COUNT(fb.engineer_id) AS `total_feedback`, SUM(fb.ra
我一直在尝试做这个程序,但我被卡住了,我仍然是一个初学者,任何帮助将不胜感激。我需要程序来做 打印一个 10 X 10 的表格,其中表格中的每个条目都是行号和列号的总和 包含一个累加器,用于计算所有表
这个计算背后一定有一些逻辑。但我无法得到它。普通数学不会导致这种行为。谁能帮我解释一下原因 printf ("float %f\n", 2/7 * 100.0); 结果打印 1.000000 为什么会
我想计算从 0 到 (n)^{1/2} - 1 的数字的 AND每个数字从 0 到 (n)^{1/2} - 1 .我想在 O(n) 中执行此操作时间,不能使用 XOR、OR、AND 运算。 具体来说,
如何在 Excel 中将公式放入自定义数字格式?例如(出于说明目的随机示例), 假设我有以下数据: 输入 输出 在不编辑单元格中的实际数据的情况下,我想显示单元格中的值除以 2,并保留两位小数: 有没
每次我在 Flutter 应用程序中调用计算()时,我都会看到内存泄漏,据我所知,这基本上只是一种生成隔离的便捷方法。我的应用程序内存占用增加并且在 GC 之后永远不会减少。 我已将我的代码简化为仅调
我有数字特征观察 V1通过 V12用于目标变量 Wavelength .我想计算 Vx 之间的 RMSE列。数据格式如下。 每个变量“Vx”以 5 分钟的间隔进行测量。我想计算所有 Vx 变量的观测值
我正在寻找一种使用 C 语言计算文件中未知字符数的简单方法。谢谢你的帮助 最佳答案 POSIX 方式(可能是您想要的方式): off_t get_file_length( FILE *file ) {
我正在使用 Postgres,并且我正试图围绕如何在连续日期跨度中得出第一个开始日期的问题进行思考。例如 :- ID | Start Date | End Date =================
我有一个订单表格,我在其中使用 jQuery 计算插件来汇总总数。 此求和工作正常,但生成的“总和”存在问题。总之,我希望用逗号替换任何点。 代码的基础是; function ($this) {
我在使用 double 变量计算简单算术方程时遇到问题。 我有一个具有 double 属性 Value 的组件,我将此属性设置为 100。 然后我做一个简单的减法来检查这个值是否真的是 100: va
我在这里看到了一些关于 CRC 32 计算的其他问题。但没有一个让我满意,因此是这样。 openssl 库是否有任何用于计算 CRC32 的 api 支持?我已经在为 SHA1 使用 openssl,
当我在PHP日期计算中遇到问题时,我感到惊讶。 $add = '- 30 days'; echo date('Y-m-01', strtotime($add)); // result is 2017-
我正在使用 javascript 进行练习,我编写了这个脚本来计算 2 个变量的总和,然后在第三个方程中使用这个总和!关于如何完成这项工作的任何想法都将非常有用! First Number:
我有一个来自EAC的提示单和一个包含完整专辑的FLAC文件。 我正在尝试制作一些python脚本来播放文件,因为我需要能够设置在flac文件中开始的位置。 如何从CueSheet格式MM:SS:FF转
这个问题已经有答案了: Adding two numbers concatenates them instead of calculating the sum (24 个回答) 已关闭去年。 我有一个
4000 我需要上面字段 name="quantity" 和 id="price" 中的值,并使用 javascript 函数进行计算,并将其显示在字段 id= 中仅当我单击计算按钮时才显示“总
我是一名优秀的程序员,十分优秀!