【发布时间】:2021-10-22 15:46:35
【问题描述】:
我为一个问题创建了一个 C 程序,但我遇到了下面给出的一些问题。我在这个程序中使用了逻辑和条件运算符。
//Question - c4.d.f
/*
A certain grade of steel is graded according to the following conditions:
(i)Hardness must be greater than 50
(ii)Carbon content must be less than 0.7
(iii)Tensile strength must be greater than 5600
The grades are as follows:
Grade is 10 if all three conditions are met
Grade is 9 if conditions (i) and (ii) are met
Grade 8 if conditions (ii) and (iii) are met
Grade 7 if conditions (i) and (iii) are met
Grade 6 if only one condition is met
Grade is 5 if none of the conditions are met
Write a program, which will require the user to give values of hardness,
carbon content, and tensile strength of the steel under consideration and
output the grade of the steel.
*/
#include<stdio.h>
int main()
{
int hrd,tslstr;
float crbct;
int con1, con2, con3;
printf("Please enter the values of the Hardness, Carbon content, Tensile Strength\n");
scanf("%d%f%d",&hrd,&crbct,&tslstr);
//conditions
hrd>50?con1=1:(con1=0);
crbct<0.7?con2=1:(con2=0);
tslstr>5600?con3=1:(con3=0);
//Calculating Grades
if( con1 && con2 && con3)
printf("Grade 10\n");
else if( con1 && con2 )
printf("Grade 9\n");
else if( con2 && con3 )
printf("Grade 8\n");
else if( con1 && con3 )
printf("Grade 7\n");
else if( con1 || con2 || con3 )
printf("Grade 6\n");
else
printf("Grade 5\n");
return 0;
}
我运行程序并给出值(如下所示),所以我打印了“Grade 5”,但它打印的是“Grade 6”。请帮我找出这段代码中的问题。
Please enter the values of the Hardness, Carbon content, Tensile Strength
50
0.7
5600
Grade 6
【问题讨论】:
-
请学习如何使用调试器在监控变量和theif值的同时逐句执行代码。
-
并且不要做像
hrd>50?con1=1:(con1=0);这样的陈述。首选简单的if else语句,因为它会使代码更易于阅读和理解,但如果您绝对必须使用三元表达式,请在赋值的右侧使用它(con1 = hdr > 50 ? 1 : 0;,或者考虑到布尔结果是1为真,0为假:con1 = hdr > 50;) -
... 如果您觉得自己不知道如何使用调试器,请首先打印 con1、con2 和 con3 的值。它应该为您提供有关哪个有问题的线索。例如,您可能会发现 con2 为 1。如果发生这种情况,您将打印 crbct 的值。如果您随后看到它是例如 0.6999999,您就会知道是浮点问题导致了您的问题。
标签: c if-statement conditional-statements logical-operators