如何将局部变量初始化为C++的未知值

How to initialize local variable to unkown value C++

本文关键字:C++ 未知 初始化 局部变量      更新时间:2023-10-16

试图让我的第一篇文章正确,所以在这里。

我遇到了这个问题,但一直无法弄清楚。我不断收到错误:

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是一个习惯。