通用产品code挑战 [英] Universal Product Code challenge

查看:108
本文介绍了通用产品code挑战的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,如何正确使用%d个 C语言。我目前正在C编程的课程和我们得到一个小挑战,编辑从教科书code(C编程一种现代方法,K. N. KING)。
我们的目标是在酒吧code三个输入编辑code:

I am curious how to correctly use %d in the C language. I am currently taking a course in C programming and we were given a small challenge to edit a code from the textbook (C Programming A Modern Approach, K. N. KING). The goal was to edit the code from three inputs of the bar code:


  • 第1位,第5和第5要持续到一个单一的输入,或

  • 在一次所有11位。

在文字说明操作的方式,我相信%1D 允许输入的整数被单独分配给相应的变量。
下面是编辑code。

In the way the text explains the operator, I believe that %1d allows the entered integers to be individually assigned to the corresponding variable. Below is the edited code.

#include <stdio.h>

int main(void)
{

    /* 11 integers that come from the bar code of the product, 
    then 2 intermediate variables for calulation, and lastly the final answer.*/

    int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total;    

    printf("Enter the 11 digit Universal Product Code: ");
    scanf("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", &d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5);

    // The steps for each calculation from the textbook.
    first_sum = d + i2 + i4 + j1 + j3 + j5;
    second_sum = i1 + i3 + i5 + j2 + j4;
    total = 3 * first_sum + second_sum;

    // Prints check digit for given product code.
    printf("Check Digit: %d\n", 9 - ((total-1) % 10));
    return 0;
}


然而,当我运行程序(与原方案相同的麻烦),它不接受11位输入为11个独立的数字,只是作为一个大数目。相反,它仍然需要输入每个整数后受到打击。整数可以读取和赋值给变量这样?


However when I run the program (same trouble with the original program) it does not accept the 11 digit input as 11 separate numbers, only as one large number. Instead it still requires enter to be hit after each integer. Can integers be read and assigned to variables this way?

推荐答案

由于code以下,如果你输入123,然后preSS进入,它会打印1 2 3。

Given the code below, if you type "123" and then press enter, it will print "1 2 3".

int main( void )
{
    int a, b, c;

    printf( "Enter a three digit number\n" );
    if ( scanf( "%1d%1d%1d", &a, &b, &c ) != 3 )
        printf( "hey!!!\n" );
    else
        printf( "%d %d %d\n", a, b, c );
}

这是说,%1D 将一次读取一个数字。

下面的例子来自于C11规范草案第7.21.6.2

The following example comes from section 7.21.6.2 of the draft C11 specification

EXAMPLE 2 The call:
    #include <stdio.h>
    /* ... */
    int i; float x; char name[50];
    fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name);

with input:
    56789 0123 56a72
will assign to i the value 56 and to x the value 789.0, will skip 0123,
and will assign to name the sequence 56\0. The next character read from 
the input stream will be a.


就是这样它一直,所以如果你的编译器不能做到这一点,你需要获得一个新的编译器。


That's the way it's always been, so if your compiler doesn't do that, you need to get a new compiler.

这篇关于通用产品code挑战的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆