浮点变量在开关状态内不起作用
Float Variable Not Working Inside Switch Statment
所以这个程序应该使用for循环收集7天的天气温度,然后基本上只是将它们打印回用户,平均温度和最高记录温度。请记住,以下代码段是一个更大的程序的一部分。无论如何,问题似乎是"highest_temp1"浮点变量。当我运行程序时,它会产生某种错误代码,而不是最高温度。这段代码在单独的源文件中进行了测试,它没有问题。
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
本周的最高温度是24,但它正在打印"最高温度:3.45857e+032"
每次我运行程序时都会出现这个确切的"错误代码",它不会改变。
我是新手,因此为什么我不能上传照片。
任何帮助将不胜感激。我在大学里做一个小作业。这是我的第一个问题,所以放轻松!!
您尚未为变量highest_temp1赋值,并且正在将其与另一个值进行比较。
基本上,在比较之前,您需要先为其分配一个值。
highest_temp1 = 10.00
(或它应该包含的任何内容)
你还没有初始化highest_temp1
(或者highest_temp1
:在那之后我就停止了寻找)。
accumulated_temp相同,未初始化。 可以通过
float accumulated_temp1(0);
使用变量前初始化变量
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
对于浮点数条件,如果语句 switch 在浮点数的情况下无法工作,则 switch 仅适用于整数。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么 OpenService() 在我检查窗口服务状态时不起作用?
- 浮点变量在开关状态内不起作用