我正在尝试学习C ++,并且遇到有关时间格式的小型转换程序的问题。
#include <iostream>
using namespace std;
void conversion(int hours, int minutes) {
if (hours > 12) {
hours -= 12;
minutes = minutes;
}
else
hours = hours;
minutes = minutes;
cout << hours << ":" << minutes << endl;
}
void output(int hours, int minutes) {
cout << hours << ":" << minutes;
}
int main() {
int hours, minutes;
cout << "Enter the hours: ";
cin >> hours;
cout << "Enter minutes: ";
cin >> minutes;
conversion(hours, minutes);
output(hours, minutes);
}
在main函数中,输出调用未接收小时和分钟的更新值。
答案 0 :(得分:0)
这与时间格式无关。一个显示相同问题的小得多的程序是:
#include <iostream>
using namespace std;
void f(int i) {
i = 20;
}
int main() {
int i = 10;
f(i);
cout << "i is still " << i << endl;
}
问题是参数列表中的int i
表示“按值传递”。该函数获取值的副本。当函数退出时,您对该副本所做的任何更改都将被丢弃。通过引用(void f(int& i)
)或通过指针(void f(int *pi)
)传递。在教科书中查找参考和指针。
您的功能中还存在许多问题:
void conversion(int hours, int minutes) {
if (hours > 12) {
hours -= 12;
minutes = minutes; // This line does nothing.
}
else
hours = hours; // This line does nothing.
minutes = minutes; // This line will get executed even if hours was originally
// >12. (Only the hours=hours line is covered by the else).
cout << hours << ":" << minutes << endl;
}
你可能想要:
void conversion(int& hours, int& minutes) {
if (hours > 12) {
hours -= 12;
}
cout << hours << ":" << minutes << endl;
}