Hỏi về đoạn code có sử dụng scanf_s và while

Đề bài: Viết chương trình nhập lãi xuất năm r (%), tiền vốn p và thời hạn gởi tiền n (năm). Mỗi trị nhập phải cách nhau bởi dấu “,”. In ra vốn tích lũy a của từng năm. Chương trình có kiểm tra nhập thiếu hoặc nhập lỗi.

Program c tính lãi xuất nhập vào có dấu phẩy.
Các pro cho e hỏi n=scanf_s() nghĩa là gì ạ? Với lại dòng while ngay dưới có tác dụng gì ạ? Với cả khi nào thì n=EOF ạ? Thanks các pro.

#include <stdio.h> 

int main() {
    double rate, balance;   
    unsigned year, period, n;     
    do {
        printf("Nhap lai suat, tien von, thoi han: ");   
        n = scanf_s("%lf,%lf,%u", &rate, &balance, &period);    
        while (getchar() != '\n') {}   
        if (n != 3 || n == EOF)     
            printf("Nhap thieu hoac nhap loi!\n"); 
    
    } while (n != 3 || n == EOF);

    printf("Lai suat: %g%%\n", rate * 100); 
    printf("Von ban dau: %g\n", balance);  
    printf("Thoi han: %u nam\n", period); 
    printf("%3s%10s\n", "Nam", "Von");   
    for (year = 1; year <= period; ++year) {
        balance *= 1 + rate;    
        printf("%3u%10g\n", year, balance);
    }  
    return 0;
}

merged to the #1 post by noname00

Nó trả về số format string đã đọc được.

Như code của bạn bên trên, có 3 format string %lf, %lf, %u ứng với 3 đối số là &rate, &balance, &period.

Nếu chuỗi nhập vào của bạn là:

123,456,789

Thì nó sẽ return 3.

123,456

Sẽ return 2.

Còn EOF thì = end of file. Tức nó sẽ trả về EOF nếu đọc được ký tự kết thúc file.
Nhập trên consosle thì nó là Ctrl + D hoặc Ctrl + Z.

http://www.cplusplus.com/reference/cstdio/scanf/

Return Value

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file .

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?