如何将局部变量初始化为C++的未知值
How to initialize local variable to unkown value C++
试图让我的第一篇文章正确,所以在这里。
我遇到了这个问题,但一直无法弄清楚。我不断收到错误:
error C4700: uninitialized local variable 'miles' used
我已经搜索了所有 StackOverflow 并不断遇到相同的答案:我必须初始化我的局部变量,但是当我这样做时,我正在创建一个设置值。我想将局部变量"miles"设置为未知值,因为我希望用户能够在程序运行时设置该值。
一切都运行良好,直到我尝试转换结束值"英里"以便它被截断。
如果我使用了不正确的术语,请纠正我。刚从子宫里出来编程。并提前感谢大家。
问题: 编写一个程序,提示汽车油箱的容量(以加仑为单位(以及汽车可以行驶的每加仑英里数。该程序输出汽车无需加油即可行驶的英里数。为容量输入的数字必须允许输入整数容量和小数单位的每加仑英里数。英里数必须输出到下一个最低整数(不带小数(。
#include "stdafx.h"
//include statement
#include<iostream>
//include namespace statement
using namespace std;
//main function
int main()
{
//variable declaration
double capacity_Gallons;
double miles_Gallon;
double miles = static_cast<int>(miles < 0 ? miles - 0.5 : miles + 0.5);
//inputting capacity of automobile
cout << "Enter the capacity of the automobile fuel in gallons: ";
cin >> capacity_Gallons;
cout << endl;
//inputting the miles per Gallons
cout << "Enter the miles per gallons the automobile can be driven: ";
cin >> miles_Gallon;
cout << endl;
//calculating miles
miles = capacity_Gallons * miles_Gallon;
//display output data
cout << "Number of miles driven wihtout refueling: " << miles << endl;
//pause system for some time for user continuation
system("pause");
} //end main
您应该完全删除该行,并将后面的行更改为double miles = capacity_Gallons * miles_Gallon;
。
与其手工制作的舍入代码,不如在显示语句中使用标准舍入函数,...<< std::lround(miles) <<
......虽然你的作业规定说你应该四舍五入,而不是像你目前所做的那样四舍五入到最接近。(所以你可以投到那里int
(。
你不需要在那里声明miles
,你可以在它有值的时候声明它。
#include<iostream>
int main()
{
//inputting capacity of automobile
double capacity_Gallons;
std::cout << "Enter the capacity of the automobile fuel in gallons: ";
std::cin >> capacity_Gallons;
std::cout << endl;
//inputting the miles per Gallons
double miles_Gallon;
std::cout << "Enter the miles per gallons the automobile can be driven: ";
std::cin >> miles_Gallon;
std::cout << endl;
//calculating miles
double miles = capacity_Gallons * miles_Gallon;
//display output data
std::cout << "Number of miles driven wihtout refueling: " << miles << std::endl;
//pause system for some time for user continuation
system("pause");
}
顺便说一句,using namespace std
是一个坏习惯。
相关文章:
- 继承期间显示未知行为的子类
- 输入中的字符串数未知(以字母表示)
- 具有未知值时的时间复杂性
- 链表中写入访问冲突的未知原因
- 正在生成未知类实例
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 读取文件时运行时的未知行为
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 初始化多个未知基类
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 如何存储未知次数迭代的输入?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 编译 Boost 时在 OS X 上的"ld:未知选项:-soname"
- 未知的 CMake 命令"create_single_source_cgal_program"
- 如何在C++中循环访问未知对象方法?
- Coursera :自动评分器的未知信号 11
- 即使直接从官方示例中复制,也找不到未知类型名称QML_ELEMENT和 QML 模块
- 未知的 GCC 链接器错误,但已成功构建
- 如何从未知视图中声明范围::v3::View 变量
- std::string.size() 未知行为