布尔函数没有给出正确答案
Boolean function not giving right answer
我的布尔函数check_gift有问题。当礼物在商店中时,它给出的值是假的......
我做错了什么?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <string>
#include <cassert>
using namespace std;
typedef vector<string> Wishes;
int size(Wishes& w){ return static_cast<int>(w.size()); }
struct Wishlist
{
double budget;
Wishes wishes;
};
struct Gift
{
double price;
string name;
};
typedef vector<Gift> Giftstore;
int size(Giftstore& g) { return static_cast<int>(g.size()); }
void read_wishlist_into_struct(ifstream& infile, Wishlist& wishlist)
{
double b;
infile>>b;
wishlist.budget=b;
int i=0;
string name;
getline(infile,name);
while(infile)
{
wishlist.wishes.push_back(name);
i++;
getline(infile,name);
}
infile.close();
}
void show_wishlist(Wishlist wishlist)
{
cout<<"Budget: "<<wishlist.budget<<endl<<endl;
cout<<"Wishes: "<<endl;
for(int i=0; i<size(wishlist.wishes); i++)
{
cout<<wishlist.wishes[i]<<endl;
}
cout<<endl;
}
void read_giftstore_into_vector(ifstream& infile, Gift& gift, Giftstore& giftstore)
{
double p;
string name;
int i=0;
infile>>p;
while(infile)
{
gift.price=p;
getline(infile,name);
gift.name=name;
giftstore.push_back(gift);
i++;
infile>>p;
}
infile.close();
}
void show_giftstore(Giftstore giftstore)
{
cout<<"All possible gifts in giftstore: "<<endl<<endl;
for(int i=0; i<size(giftstore); i++)
{
cout<<giftstore[i].price<<"t"<<giftstore[i].name<<endl;
}
cout<<endl;
}
bool check_gift(Giftstore giftstore, string giftname)
{
int i=0;
while(i<size(giftstore))
{
if(giftstore[i].name==giftname)
{
return true;
}
else
{
i++;
}
}
return false;
}
void clear(Wishlist& b)
{
b.budget=0;
while(!b.wishes.empty())
{
b.wishes.pop_back();
}
}
void copy(Wishlist a, Wishlist& b)
{
b.budget=a.budget;
for (int i=0; i<size(b.wishes); i++)
{
b.wishes.push_back(a.wishes[i]);
}
}
int main ()
{
ifstream infile2("giftstore.txt");
Gift gift;
Giftstore giftstore;
read_giftstore_into_vector(infile2, gift, giftstore);
show_giftstore(giftstore);
string giftname;
giftname=("dvd Up van Pixar");
bool x;
x=check_gift(giftstore, giftname);
cout<<"in store?: "<<x<<endl;
return 0;
}
您忘记在check_gift
函数结束时返回false
bool check_gift(Giftstore giftstore, string giftname)
{
int i=0;
while(i<size(giftstore))
{
if(giftstore[i].name==giftname)
{
return true;
}
else
{
i++;
}
}
return false;
}
函数末尾没有return false;
;因此,如果没有找到礼物,程序将从末尾掉下来并给出未定义的行为。
如果启用警告,编译器应向您发出警告。
您需要
在check_gift()
末尾添加return false
。
相关文章:
- C++ 中 pow() 函数的输出没有给出准确的答案
- 函数从指针 c++ 中获取错误的值并返回错误的答案
- c++:运行一个函数 8 次,并将每个答案添加到数组或 JSON 中
- 阶乘函数只返回C++中输入的答案
- 给定一个整数 N>0,区间 [0, 2^N) 中有多少个整数正好有 N-1 个设置位?编写一个返回正确答案的简短函数
- 为什么在C++算术函数中加".0"会给出小数点的答案?
- 在 c++ 中将模板与类一起使用时,类成员函数的答案错误?
- 无法在 for 循环中的 pow 函数上输出答案
- 为什么我的函数返回一个整数,尽管我已经将答案指定为浮点数
- 使用幂函数的计算给出了大数字的错误答案
- 试图弄清楚如何使用递归来获得与另一个函数相同的答案
- void 函数使用相同的变量打印两个不同的答案
- ABS 函数在 C++ 中没有给出正确的答案
- 布尔函数的错误答案
- 布尔函数没有给出正确答案
- 无法计算如何从联机答案中返回c++函数的多个值
- 函数的答案不正确
- 无法从非常简单的函数中获得正确答案
- C++构造函数并使其显示默认答案
- 二项式系数函数C++错误答案 n>13