#include<stdio.h>
#include<stdlib.h>
int input, x, c=0;
for (input=1; input<=100; input )
{
while(input != 0)
{
x = input%10;
c = c*10 x;
input = input/10;
}
printf("Reverse Number is : %d", c);
}
這是反向編號代碼,但此代碼列印負值。為什么此代碼列印負值?
uj5u.com熱心網友回復:
是的,您絕對可以在 for 回圈中使用 while 回圈。不過,這樣做時你應該小心。我注意到您的代碼存在一些問題。
首先,你的模板不正確,所以它甚至編譯都很奇怪,所以讓我快速為你解決這個問題
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int input, x, c = 0;
for (input = 1; input <= 100; input )
{
while(input != 0)
{
x = input % 10;
c = c * 10 x;
input = input / 10;
}
printf("Reverse Number is : %d\n", c);
}
return 0;
}
現在讓我們看看inputfor 回圈中的變數會發生什么:
input = 1while(input != 0)當while回圈結束時,input == 0- for 回圈再次開始,
input == 1。
所以,結果,for 回圈變成了一個無限回圈,其中input變數總是等于 1。為了解決這個問題,我們需要在回圈中引入一個臨時變數,以便input保持它的值直到下一次迭代。讓我們這樣做。
for (input = 1; input <= 100; input )
{
int temp = input;
while(temp != 0)
{
x = temp % 10;
c = c * 10 x;
temp = temp / 10;
}
printf("Reverse Number is : %d\n", c);
}
下一個問題是沒有地方可以重置c. 因此它只會變大并最終溢位。為了解決這個問題,我們需要c在 while 回圈開始之前重置 的值。
for (input = 1; input <= 100; input )
{
int temp = input;
c = 0;
while(temp != 0)
{
x = temp % 10;
c = c * 10 x;
temp = temp / 10;
}
printf("Reverse Number is : %d\n", c);
}
而且,就是這樣!
結果將如下所示:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int input, x, c = 0;
for (input = 1; input <= 100; input )
{
int temp = input;
c = 0;
while(temp != 0)
{
x = temp % 10;
c = c * 10 x;
temp = temp / 10;
}
printf("Reverse Number is : %d\n", c);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367269.html
標籤:C
上一篇:無符號整數
