"Variable 'DivisionCount' should beinteger datatype."? integer datatypes?
이전 댓글 표시
So I am stuck on this computer feedback I received on my homework. Sorry for all the words... this is what I had to do.
"The test suite assigns a random number to the variable Number. Write a script that uses a while loop to repeatedly divide this number by 7 until the value remaining is less than 1. Assign the result to the variable WhatsLeft. Keep track of the number of divisions required and assign to the integer variable DivisionCount."
This is my code:
DivisionCount = 0
while Number > 1
Number = Number / 7
DivisionCount = DivisionCount + 1
end
WhatsLeft = Number
DivisionCount = DivisionCount
I get this comment: "Variable DivisionCount should beinteger datatype." I don't know how to fix this.
답변 (2개)
John D'Errico
2017년 2월 24일
Lots of them.
help uint8
help uint16
help uint32
help uint64
help int8
help int16
help int32
help int64
댓글 수: 7
Michael Scully
2017년 2월 24일
@Michael: Start with
DivisionCount = uint64(0)
Then the rest of the code will work.
Michael Scully
2017년 2월 24일
Adam
2017년 2월 24일
You should be able to do it on the final line. I don't know why Matlab coursework would specify that a counter needs to be an integer data type. Sure, we all know a counter will be an integer and in C++ we would declare it as such, but in Matlab since we don't declare variables with a type every number is a double by default. Trying to crowbar integer datatypes into maths generally leads to a mess like this so most of us just accept that we have a double data type containing something that we know should always be integer valued. This does lead to some unpleasant surprising when doing e.g. indexing, but less so than trying to force a load of maths into integer types.
As an aside, when passing such numbers around between functions, I often make use of
validateattributes( myVariable, { 'double' }, { 'integer' } )
It is counter-intuitive, but useful, though way beyond what you are being asked for!
But since your coursework does require this then cast it at the end so you don't have to deal with issues of integer maths.
Michael Scully
2017년 2월 24일
편집: Walter Roberson
2017년 2월 24일
No, just add
DivisionCount = int16( DivisionCount );
at the end (or any of the others that John D'Errico posted)
Dewey Phillips
2017년 3월 1일
편집: Dewey Phillips
2017년 3월 1일
This code worked for me:
DivisionCount = 0;
while Number > 1
Number = Number / 7;
DivisionCount = DivisionCount + 1;
end
WhatsLeft = Number;
disp(WhatsLeft)
DivisionCount = uint8(DivisionCount);
disp(DivisionCount)
Jonathan Truitt
2017년 2월 28일
0 개 추천
They making while two loops. One for your first to variables. The second for your last variable. The last loop will need a break. Also, make your first line of code DivisionCount = uint(0).
Hope that helps!
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!