C语言程序设计精髓第四周编程

检测用户错误输入

题目内容:

根据scanf()的返回值判断scanf()是否成功读入了指定的数据项数,使程序在用户输入123a时,能输出如下运行结果:

123a↙

Input error!

#include <stdio.h>

int main() {
   
    int a, b;
    if (scanf("%d %d", &a, &b) == 2) {
   
        printf("a = %d, b = %d\n", a, b);
    } else {
   
        printf("Input error!");
    }
    return 0;
}

闰年判断

题目内容:

从键盘任意输入一个公元年份(大于等于1),判断它是否是闰年。若是闰年输出“Yes”,否则输出“No”。要求对输入数据进行合法性判断。

已知符合下列条件之一者是闰年:

(1)能被4整除,但不能被100整除;

(2)能被400整除。

#include <stdio.h>

int main() {
   
    int a;
    scanf("%d", &a);
    if (a > 999 && a < 10000) {
   
        if ((a % 4 == 0 && a % 100 != 0) || a % 400 == 0) {
   
            printf("Yes\n");
        } else {
   
            printf("No\n");
        }
    } else {
   
        printf("Input error!\n");
    }
    return 0;
}

程序改错v1.0

题目内容:

下面代码的功能是将百分制成绩转换为5分制成绩,具体功能是:如果用户输入的是非法字符或者不在合理区间内的数据(例如输入的是a,或者102,或-45等),则程序输出 Input error!,否则将其转换为5分制输出。目前程序存在错误,请将其修改正确。并按照下面给出的运行示例检查程序。

#include<stdio.h>
   int main()
   {
   
       int score;
       char grade;
       printf("Please input  score:");
       scanf("%d", &score);
       if (score < 0 || score > 100)   
             printf("Input error!\n");
        else if (score >= 90) 
             grade = 'A’;
        else if (score >= 80)
             grade = 'B';   
        else if (score >= 70)
             grade = 'C';  
        else if (score >= 60)
             grade = 'D'; 
        else
             grade = 'E'; 
        printf("grade:%c\n", grade);
        return 0;
}
#include<stdio.h>

int main() {
   
    int score;
    char grade;
    printf("Please input score:\n");
    scanf("%d", &score);
    if (score < 0 || score > 100) {
   
        printf("Input error!\n");
    } else {
   
        if (score >= 90)
            grade = 'A';
        else if (score >= 80)
            grade = 'B';
        else if (score >= 70)
            grade = 'C';
        else if (score >= 60)
            grade = 'D';
        else
            grade = 'E';
        
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值