问题:
第一次扫描是用户请求的转换次数。以下是将要转换的内容。 重点是计算编写这些数字所需的LED数量,如下图Numbers in LED
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, j, k, leds, a, clean;
//here i scan the number of times the program will be executed
scanf ("%i", &a);
int n[a], l[a];
char c[101] = {0}; //the string where the numbers will be armazened
for (i=0; i< a; i++)
{
scanf ("%i", &n[i]); //here i get the numbers
}
for (i=0; i<a; i++)
{
sprintf(c, "%d", n[i]);
leds = 0; //where the numbers of leds needed will be armazened
while(c[j] != '\0')
{
if(c[j] == '0')
{
leds = leds + 6;
}
else if(c[j] == '1')
{
leds = leds + 2;
}
else if(c[j] == '2')
{
leds = leds + 5;
}
else if(c[j] == '3')
{
leds = leds + 5;
}
else if(c[j] == '4')
{
leds = leds + 4;
}
else if(c[j] == '5')
{
leds = leds + 5;
}
else if(c[j] == '6')
{
leds = leds + 6;
}
else if(c[j] == '7')
{
leds = leds + 3;
}
else if(c[j] == '8')
{
leds = leds + 7;
}
else if(c[j] == '9')
{
leds = leds + 6;
}
clean = j;
j++;
}
l[i] = leds; //where the number of leds of each will be armazened to be printed afterwards
}
for (i = 0; i<a; i++)
{
printf("%i\n", l[i]);
}
}
我的意见: 3 115380 2819311 23456
我得到的输出: 27(唯一正确的) 2 0
我应该得到什么: 27 29 25
我只是不知道我做错了什么,但我认为它是c []和sprintf。但我该怎么办?
很抱歉,如果英语不对,
答案 0 :(得分:0)
您尚未初始化j
sprintf(c, "%d", n[i]);
leds = 0; //where the numbers of leds needed will be armazened
应该是
sprintf(c, "%d", n[i]);
j = 0;
leds = 0; //where the numbers of leds needed will be armazened
答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, j, k, leds, a, clean;
//here i scan the number of times the program will be executed
scanf ("%i", &a);
int n[a], l[a];
char c[101] = {0}; //the string where the numbers will be armazened
int numLeds[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
for (i=0; i< a; i++)
{
scanf ("%i", &n[i]); //here i get the numbers
}
for (i=0; i<a; i++)
{
sprintf(c, "%d", n[i]);
leds = 0; //where the numbers of leds needed will be armazened
int j = 0;
while(c[j] != '\0')
{
// 48 = zero in ASCII code
if (c[j] < 48 || c[j] > 48 + 9)
continue;
int digit = c[j] - 48;
leds += numLeds[digit];
clean = j;
j++;
}
l[i] = leds; //where the number of leds of each will be armazened to be printed afterwards
}
for (i = 0; i<a; i++)
{
printf("%i\n", l[i]);
}
}