首先,让我向您展示代码:
// calculate grand total
if(unitsPurchased >= 10,19)
{
discount = .20;
totalCost = totalCost - (totalCost * discount);
cout << fixed << setprecision(2);
cout << "\tBecuase you purchased " << unitsPurchased << " Units,\n\tYou get a 20% discount!" << "The grand total is: $" << totalCost << endl;
}
如果某人在20%
之间购物,我会尝试给予10 to 19 items
折扣。如何更改我的if语句以反映这一点?我尝试使用AND (&&)
,但没有用。如何设置两个数字之间的范围?
答案 0 :(得分:4)
您要查找的语句是以下之一:
if (unitsPurchased > 10 && unitsPurchased < 19) { // exclude 10, 19
if (unitsPurchased >= 10 && unitsPurchased < 19) { // include 10, exclude 19
if (unitsPurchased >= 10 && unitsPurchased <= 19) { // include 10, 19
类似valA, valB
的表达式实际上是逗号运算符的使用,该运算符将同时评估valA
和valB
,但得出 single 值{{1 }}。
在您的特定情况下,由于逗号运算符的优先级相对较低,因此更为复杂,因此valB
的意思是unitsPurchased >= 10, 19
,等于:
(unitsPurchased >= 10), 19
; unitsPurchased >= 10
; 19
。由于19
不为零,因此它被认为是正确的。因此,由于每次购买都会带来20%的折扣:-)
答案 1 :(得分:0)
您可以这样做:
if(unitsPurchased > 10 && unitsPurchased < 19){
discount = 0.2;
}
此if语句检查unitsPurchased
是否大于10 ,是否小于19,这正是您想要的。
答案 2 :(得分:0)
您必须使用Auth
(和)运算符:
import { Link, Redirect } from "react-router-dom";
const Auth = (props) => {
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});
const handleFormData = e =>
setFormData({
...formData,
[e.target.name]: e.target.value
});
const { username, email, password } = formData;
const handleSubmit = e => {
e.preventDefault();
props.login({
username,
email,
password
});
// Perhaps also check if login was successful?
history.push("/posts");
}
return (
<div>
<form
onSubmit={handleSubmit}
>
<input
type="text"
name="username"
placeholder="Username"
onChange={handleFormData}
value={username}
/>
<input
type="email"
name="email"
placeholder="Email"
onChange={handleFormData}
value={email}
/>
<input
type="password"
name="password"
placeholder="Password"
onChange={handleFormData} value={password} />
<button type="submit">
Login
</button>
</form>
<Link to="/posts">Go to posts</Link>
</div>
);
}
答案 3 :(得分:0)
其他答案是正确的,如果有人遇到这个问题,我想提个醒。
不要写10 <= unitsPurchased <= 19
。这将是许多语言(不是全部)的错误陈述。如果unitsPurchased
为20,则语句的第一部分将是正确的,即使第二部分是错误的,它也将返回true
。
这是我在第一次编程考试中犯的一个错误。
答案 4 :(得分:0)
if(unitsPurchased > 10 && unitsPurchased < 19){
}
这样做。