gpt4 book ai didi

c++ - 对初始化时使用的未初始化局部变量感到困惑?

转载 作者:行者123 更新时间:2023-11-30 01:18:55 24 4
gpt4 key购买 nike

当我相信我已经初始化时,我收到了一个未初始化的局部变量错误。错误读取未初始化的局部变量 wk1 being used (It's wk1-wk5)。

代码如下:

#include <iostream>

using namespace std;

const double tax = 0.14;

int main()
{

int wk1,wk2,wk3,wk4,wk5;
wk1,wk2,wk3,wk4,wk5 = 0;

int thours = wk1 + wk2 + wk3 + wk4 + wk5; <------------ This is the error line.
thours = 0;

double payrate;
payrate = 0;

double gross = thours * payrate;
double taxes = tax * gross;
double net = gross - taxes;
double clothes = 0.10 * net;
double supplies = 0.10 * net;
double remaining = net - clothes - supplies;
double bonds = 0.25 * remaining;
double pbonds = 0.50 * bonds;

bonds = 0;
gross = 0;
net = 0;
clothes = 0;
supplies = 0;
remaining = 0;

cout << "Please enter the payrate for employee." << endl;
cin >> payrate;
payrate = 0;

cout << "Please enter employee's total hours for week one:" << endl;
cin >> wk1;
wk1 = 0;

cout << "Please enter employee's total hours for week two:" << endl;
cin >> wk2;
wk2 = 0;

cout << "Please enter employee's total hours for week three:" << endl;
cin >> wk3;
wk3 = 0;

cout << "Please enter employee's total hours for week four:" << endl;
cin >> wk4;
wk4 = 0;

cout << "Please enter employee's total hours for week five:" << endl;
cin >> wk5;
wk5 = 0;

cout << "Here is income before taxes: " << gross << endl;
cout << "Here is income after taxes: " << net << endl;
cout << "Here is clothes and accesories: " << clothes << endl;
cout << "Here is School supplies: " << supplies << endl;
cout << "Here is personal bonds: " << bonds << endl;
cout << "Here is parents bonds: " << pbonds << endl;

return 0;
}

最佳答案

wk1,wk2,wk3,wk4,wk5 = 0;

这一行是一个逗号运算符表达式,相当于:

wk5 = 0;

因为像 wk1 这样的表达式没有副作用。只有变量 wk5 被赋值,其他变量仍未初始化。你可以这样做:

wk1 = wk2 = wk3 = wk4 = wk5 = 0;

关于c++ - 对初始化时使用的未初始化局部变量感到困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21793529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com