c - 程序返回错误值
问题描述
我的 C 代码的以下部分有问题:
// reading pairs of parameters from input file
while((read = fscanf(input_file, "%d %d\n", &type, &col)) > 0 ) {
// checking reading errors
if (read != 2 || (type < 0 && type > 4) || (col > 9)) {
printf("Invalid input file format\n");
return 2;
}
// putting tetromino corresponding to given parameters to the field
if (put_tetromino(field, type, col) != 0) {
// if result is not 0, the tetromnio is out of range. Returning error
printf("Tetromino is out of field\n");
return 2;
}
}
输入文件如下所示:
5 0
3 9
2 9
2 4
..
在上面的代码部分中,我想检查输入文件是否具有正确的格式。我应该有 2 列:第一列(type)必须是 0 到 4 之间的值,第二列(col)必须是 0 到 9 之间的值。如果输入文件包含错误的格式,例如:
9 8
4 9
2 5
..
我想返回 2。但程序不返回 2,它在主函数结束时返回 0。
解决方案
表达式(type < 0 && type > 4)
总是错误的——一个数字不能既大于四又小于零。您应该使用 an||
而不是&&
那里:
if (read != 2 || type < 0 || type > 4 || col > 9) {
推荐阅读
- javascript - 在 Firebase 上快速重置用户数据
- wordpress - 根据订单内容更改 woocommerce 客户电子邮件的回复地址
- ruby - 如何使用法拉第发送 json
- javascript - 克隆一个 4D 多维数组
- python - ValueError:没有为 Tensorflow 2.5 中的任何变量提供梯度
- angular - RXJS:创建并链接过滤器的动态数组
- nginx - DNS 问题:NXDOMAIN 为 www.exampl.com 查找 A - 检查该域是否存在 DNS 记录
- php - Codeingeter 在本地服务器中工作,但不在生活服务器中
- pine-script - pinescript中的na()函数是什么意思?
- css - 如何为具有多个配置选项的 WordPress 插件解决 CSS