В настоящее время я работаю над проектом, который предназначен для обучения использованию функций в C++. Я работал с python на пути и имел разумное представление о функциях в коде (или, как я думал), но по какой-то причине у меня возникают некоторые тревожные ошибки, когда я передаю значения моей текущей функции.
Это весь код, моя проблема заключается в вызове narc_num (153,3), сделанном в основном. Я добавил некоторые инструкции cout в функцию narc_num, чтобы понять, почему я получаю неуловимые результаты и обнаружил, что аргумент num передается как совершенно другое число. Почему это должно быть?
#include<iostream>
#include<cmath>
using std::cin;
using std::cout;
using std::endl;
/*
Function: order_parameters
Purpose: If first is greater than second reassign the values so second is greater than first
Algorithm:
1.Pass arguments as references to first and second
2.if statement that runs if first is greater than second
3.within if statement switch values using a temporrary variable
4.if else doesnt run nothing happens
*/
void order_parameters(long & first,long & second)//passing long references of first and second
{
if(first > second)//start if when the ref to first > ref to second
{
long temp; // initialize temp
temp = second; //value temp is = to second
second = first; //second will now be first, temp is still = to first though as well
first = temp; //second is now set = to temp, which is first. dat swap
}//end if
}
/*
Function: narc_num
Purpose: check if a number is indeed a narcisstic number
Algorithm:
1.Pass num, the number to be checked, and power, the order the number will be checked against
2.use a while loop to iterate through digits of number
-mod10 takes the last digit, the digit is raised to the power passed as an argument
-the value found is added to the total
-the number is then divided by 10 to remove the last digit, reiterates again.
3.the total found by the while loop is checked against the number passed an as argument
-if the total is equal to the number it is narcisstic.
*/
bool narc_num(long num, long power)// will return a boolean value, passing num and power integers
{
//split all digits into seperate numbers, add together raised to power
long total = 0,digit,num_copy;
bool narc = false; //value to check if number is narcissitic or not
num = num_copy;
cout << "number"<< num << endl;
while(num > 0)
{digit = num%10;
cout <<"digit" << digit << endl;
total += pow(digit,power);
cout <<"total" << total << endl;
num /= 10; //divides by 10 to go to the next digit down
}
if (total == num)
narc = true;
cout << total << endl;
return narc;
}
long check_range(long first,long last,long power)
{
bool check;
order_parameters(first,last); //make sure parameters are in correct order
for(first;first == last;first++);//iterate through all numbers from first to last
{check = narc_num(first,power); //check = True if narc number otherwise false
if (check == true)
{cout << first <<" is a narcissistic number of order " <<power<< endl;
};
cout << "gothere"<< endl;
};
cout << "dick canoe"<< endl;
}
int main(){
narc_num(153,3);
}
Вы назначаете значение num_copy (неинициализированный длинный) num рядом с верхней частью функции narc_num. Я полагаю, вы хотели назначить num_copy значение num. Вероятно, это является причиной ваших неожиданных результатов.
num
в неинициализированное значение.
for(first;first == last;first++);
Я думаю, вы имели в виду!=
И первыйfirst
имеет никакого эффекта, вы можете написатьfor(;first != last;first++);
,check_range
также должен что-то возвращать.