我是编程的初学者,我正在尝试制作Kilometer和Miles转换器应用程序。我正在为我的代码使用代码块。选择2继续给我0作为结果。这是我输入的确切代码:
#include <iostream>
using namespace std;
double choice, value1, result;
// I'm sure I messed up somewhere after this:
double value2 = .621371;
double value3 = 1.609344;
// Are these two lines ^ supposed to be here?
int main()
{
while (true) {
cout << "1. Kilometers to Miles" << endl;
cout << "2. Miles to Kilometers" << endl;
cout << "3. Exit the Application" << endl;
cout << "Please enter a choice: ";
cin >> choice;
if (choice == 3)
break;
cout << "Please enter the first value: ";
cin >> value1;
// This if statement keeps giving me 0:
if (choice == 2)
result = value1 * value2;
// I believe this part here is okay:
else if (choice == 3)
result = value1 / value3;
cout << "The result is: " << result << endl;
}
}
答案 0 :(得分:0)
以下是修复代码的方法:
1.正确使用(使您的代码更具可读性)
2. 这使您的代码无法使用您的代码而且也非常不必要:
if(choice == 3){
打破;
}
3. 您的if
/ else
/ else if
语句中的每一个都需要在其后面加上大括号:
if(whatever=whatever) {
//whatever
}
4。忘记将这些break
语句用于这个简单的程序
你错过了&#34;公里到迈尔斯&#34;
6. 退出选项已搞砸,更改
else if(choice == 3)
result = value1 / value3
以强>
else if(choice == 3) {
return 0; // To end the program
}
7。 不要double
choice
变量,它使用的数据多得多,多得多,而且数据简单int
(如果是用户输入3.1(或4.838389,等)作为输入?
8.你应该减少你的结果的精确度,(你不想要3.37374662232365英里/公里,你想要3.3英里/公里。)你可以通过添加#include <iomanip>
并添加{{{}来做到这一点。 1}}在声明什么&#34;结果&#34;之前是(即:setprecision()
)
9.在这种情况下包含整个 result = setprecision(1) value1 * value2;
命名空间是不合适的(它会使你的程序减慢ALOT),所以你应该在每个std函数之前编写std ::或者只写{{ 1}}
答案 1 :(得分:0)
我现在修复了问题。如果有人也可以在下面给我评论,这比我原来的代码要好很多吗?基本上这个新代码对你们所有人来说都更具可读性,是否更有条理?我很想得到所有关于这个更新代码的意见。
#include <iostream>
float choice, value1, result;
int main(){
while (true){
std::cout << "Please enter a choice: " << std::endl <<
"1. Kilometers to Miles" << std::endl <<
"2. Miles to Kilometers" << std::endl <<
"3. Exit the Application" << std::endl;
std::cin >> choice;
if(choice == 3){
break;
}
std::cout << "Enter the Value you would Like to Convert: ";
std::cin >> value1;
if (choice == 1){
result = value1 * 0.62137;
}
else if (choice == 2){
result = value1 * 1.609344;
}
std::cout << "The result is: " << result << std::endl;
}
}