메뉴 바로가기

서브메뉴 바로가기

본문 바로가기

logo

C/C++/MFC
(*.192.212.148) 조회 수 24101 추천 수 0 댓글 2
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

C++, scanf 에서 float, double 사용하기

 

scanf에서 double 형으로 처리하려는 분들이 많으신데 double은 지원하지 않습니다. %lf 를 사용하면 double 형으로 입력 받을 수 있습니다.

( http://whiteat.com/zbxe/49544#comment_50799 의 "처음처럼만"님께서 올려주신 댓글로 수정하였습니다. )

 

 

 

#include "stdafx.h"

 

int _tmain(int argc, _TCHAR* argv[])

{

    int a;

    double b,c,d;

    printf("키는?");

    scanf("%d",&a);

 

    printf("체중은?");

    scanf("%lf",&b);

 

 

    c = (a-100)*0.9;

    d = b-c;

    printf("키가%d 인사람의표준체중은%.1lf 이며, 현재체중과표준체중의차이는%.1lfKg이다\r\n",a,c,d);

 

    return 0;

}

 

 

 

 

  

 

 

 

 

 

 

double 사용

 

 

 

#include "stdafx.h"

 

int _tmain(int argc, _TCHAR* argv[])

{

    int a;

    double b,c,d;

    printf("키는?");

    scanf("%d",&a);

 

    printf("체중은?");

    scanf("%lf",&b);      // %lf 사용으로 double 사용가능

 

 

    c = (a-100)*0.9;

    d = b-c;

    printf("키가%d 인사람의표준체중은%.1lf 이며, 현재체중과표준체중의차이는%.1lfKg이다\r\n",a,c,d);

 

    return 0;

}

 

 

 

 

 

 

 

 

 

 

 

 

 

float 사용

 

 

 

#include "stdafx.h"

 

int _tmain(int argc, _TCHAR* argv[])

{

    int a;

    float b,c,d;

    printf("키는?");

    scanf("%d",&a);

 

    printf("체중은?");

    scanf("%f",&b);

 

 

    c = (a-100)*0.9;

    d = b-c;

    printf("키가%d 인사람의표준체중은%.1lf 이며, 현재체중과표준체중의차이는%.1lfKg이다\r\n",a,c,d);

 

    return 0;

}

 

 

float 를 double 형으로 변경하게 되면 아래처럼 원하는 결과를 얻을 수 있습니다.

 

 

 

 

 

scanf 함수 도움말

 

 

scanf 도움말을 참고해 보세요.~

 

 

int scanf ( const char * format, ... );

Read formatted data from stdin

Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

Parameters

format

C string that contains one or more of the following items:

  • Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.
  • Non-whitespace character, except percentage signs (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from stdin, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of stdin unread.
  • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from stdin and stored in the locations pointed by the additional arguments. A format specifier follows this prototype:

    %[*][width][modifiers]type

    where:
  • *

    An optional starting asterisk indicates that the data is to be retrieved from stdin but ignored, i.e. it is not stored in the corresponding argument.

    width

    Specifies the maximum number of characters to be read in the current reading operation

    modifiers

    Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument:
    h :
    short int (for d, i and n), or unsigned short int (for o, u and x)
    l :
    long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g)
    L :
    long double (for e, f and g)

    type

    A character specifying the type of data to be read and how it is expected to be read. See next table.


    • scanf type specifiers:

    type

    Qualifying Input

    Type of argument

    c

    Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.

    char *

    d

    Decimal integer: Number optionally preceded with a + or - sign.

    int *

    e,E,f,g,G

    Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4

    float *

    o

    Octal integer.

    int *

    s

    String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).

    char *

    u

    Unsigned decimal integer.

    unsigned int *

    x,X

    Hexadecimal integer.

    int *

    additional arguments

    The function expects a sequence of references as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order.
    For each format specifier in the format string that retrieves data, an additional argument should be specified.
    These arguments are expected to be references (pointers): if you want to store the result of a
    fscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like in:

    int n;
    scanf ("%d",&n);

     

     

    Return Value

    On success, the function returns the number of items succesfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens.
    In the case of an input failure before any data could be successfully read

     

     

관련 문서가 검색되었습니다.
  1. [2016/12/06] 피에조 센서 by 오퐈좁나쎄 (687) *2
  2. [2013/12/30] C++, C# 간단한 기능 비교 by WhiteAT (5289)
  3. [2013/06/20] 5명의 키를 읽어 들여 가장 큰 키와 작은 키를 구하는 프로그램을 작성하시오 by Question (11859) *1
  4. [2013/06/20] 배열 문제인데요 ㅠㅠ by Question (10690) *1
  5. [2013/05/30] WAT-AVR128, OUTPUT 실험 by WhiteAT (5876)
  6. [2013/05/29] 도구바, OrCAD Capture by WhiteAT (3842)
  7. [2013/05/10] C언어 문제좀 풀어주세요~ by Question (7404) *1
  8. [2013/04/25] AVR ATmega 128로 인터럽트를 이용한 LED를 점멸하는 방법 좀 알려주세요. by Question (9877) *3
  9. [2012/10/29] Visual Studio 2003 설치 by WhiteAT (9555)
  10. [2012/08/09] ZEO 모듈,매뉴얼,드라이버,라이브러리,관리툴 by WhiteAT (24263)
  • ?
    처음처럼만 2011.06.01 02:13 (*.184.137.165)

    인자를 lf로 쓰면 가능합니다. 위 문서를 제대로 읽어보시면 lf를 쓰면 되는구나 아실겁니다. f로 받으니 당연히 깨지겠죠...

  • ?
    WhiteAT 2011.06.01 07:31 (*.192.212.167)

    헛. 엄청난 실수를 해서 다른 분들께 잘못된 정보를 알려 드렸네요 ㅠㅠ

     

    지적해 주신 내용은 바로 수정하겠습니다.

     

    글 읽어 주시고, 잘못된 내용 정정해 주셔서 감사합니다.~~