c - Code isn't reading the whole string
问题描述
Problem:
The first scan is the number of converting numbers the user requests. The following are the ones that are are going to be converted. The point is to count the number of LEDs that are going to be needed to write these numbers, like the following pic 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]);
}
}
My input: 3 115380 2819311 23456
The output i get: 27 (the only one thats right) 2 0
what i should get: 27 29 25
I just don't know what im doing wrong, but i think its the c[] and the sprintf. But what should I do?
Sorry if the english isnt really right
解决方案
#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]);
}
}
推荐阅读
- sql - 使用子查询在 cte 上更新语句
- python-3.x - 如何修复 colab 上的功能工具类型错误
- c# - Identity Server 4 - 空闲时注销用户
- java - Spring JpaRepository 使用非常规命名从属性中查找实体
- angular - 如何以角度将变量名发送到休息函数?400(错误请求)。错误
- mysql - Laravel 查询选择行直到列总和 < x
- r - networkD3 和 Shiny 不显示进度条
- java - AEM 中的多字段组件 - 不保存值
- python - 网页的抓取方法
- spring-boot - ReST 或消息代理或其他用于集成本地和基于云的 Spring Boot 应用程序的方法