我正在尝试制作一个区域计算器,但我认为我通过定义长度和宽度搞砸了。 我得到一个错误说错误:未初始化的const'length'[-fpermissive] | (宽度相同) 我是编程新手
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char length;
const char width;
cout << "Please enter the your length: ";
cin >> length;
cout << "Please enter your width: ";
cin >> width;
string area =
length * width;
cout << " The area of these values is :" << area << "\n";
}
答案 0 :(得分:0)
cin >> length;
您确定const char length;
之类的变量声明吗?
const
实际上表明,您无法更改这些变量值,并且尝试这样做是未定义的行为。
另请注意,length
应该是size_t
类型,而不仅仅是unsigned char
,它最多只能容纳255个。
答案 1 :(得分:0)
您的长度和宽度变量声明不应为const
。您得到的错误是因为const
值需要在声明时初始化(赋值给它们的值)。他们不能分配给他们的值,这是cin >>
所做的。
答案 2 :(得分:0)
代码有很多问题。
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char length; // Making these const will break as soon as you try to write to it
const char width; //
cout << "Please enter the your length: ";
cin >> length; // The fact you made it a char means it will only read the first char. "10" it would read "1"
cout << "Please enter your width: ";
cin >> width;
string area = // this will not work. There is no assignment operator for char to string
length * width;
cout << " The area of these values is :" << area << "\n";
}
固定
#include <iostream>
using namespace std;
int main()
{
float length;
float width;
cout << "Please enter the your length: ";
cin >> length;
cout << "Please enter your width: ";
cin >> width;
float area = length * width;
cout << " The area of these values is :" << area << "\n";
}